首页 > 代码库 > 算法:搜索二叉树实现
算法:搜索二叉树实现
tree.h
#ifndef _TREE_H #define _TREE_H struct Node; typedef int ElementType; typedef struct Node *PtrToNode; typedef PtrToNode SearchTree; typedef PtrToNode Position; SearchTree MakeEmepty(SearchTree T); Position Find(ElementType X,SearchTree T); Position FindMin(SearchTree T); Position FindMax(SearchTree T); SearchTree Insert(ElementType X,SearchTree T); SearchTree Delete(ElementType X,SearchTree T); #endif struct Node { ElementType element; PtrToNode Left; PtrToNode Right; };
tree.c
#include <stdlib.h> #include <stdio.h> #include "tree.h" SearchTree MakeEmpty(SearchTree T) { if(T!=NULL){ MakeEmpty(T->Left); MakeEmpty(T->Right); free(T); } return NULL; } Position Find(ElementType X,SearchTree T) { if(T==NULL){ return NULL; }else if(X<T->element){ return Find(X,T->Left); }else if(X>T->element){ return Find(X,T->Right); } return T; } Position FindMin(SearchTree T) { if(T!=NULL){ while(T->Left!=NULL){ T=T->Left; } } return T; } Position FindMax(SearchTree T) { if(T!=NULL){ while(T->Right!=NULL){ T=T->Right; } } return T; } SearchTree Insert(ElementType X,SearchTree T) { if(T==NULL){ T=malloc(sizeof(struct Node)); if(T==NULL){ printf("out of space"); exit(1); }else{ T->Left=T->Right=NULL; T->element=X; return T; } }else if(X<T->element){ T->Left=Insert(X,T->Left); }else if(X>T->element){ T->Right=Insert(X,T->Right); } return T; } SearchTree Delete(ElementType X,SearchTree T) { Position P; if(T==NULL){ return NULL; }else if(X<T->element){ Delete(X,T->Left); }else if(X>T->element){ Delete(X,T->Right); }else if(T->Left!=NULL&&T->Right!=NULL){ P=FindMax(T->Right); T->element=P->element; Delete(P->element,T->Right); }else{ P=T; if(T->Left==NULL){ T=T->Right; }else{ T=T->Left; } free(P); } return T; }
算法:搜索二叉树实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。