标签:二叉树
引言:
使二叉树成为二叉查找树的性质是:对于树中的每个节点X,它的左子树中所有关键字值小于X的关键字值,而它的右子树中所有关键字值大于X的关键字值。
二叉查找树声明
struct TreeNode; typedef struct TreeNode *Position; typedef struct TreeNode *SearchTree; struct TreeNode{ ElementType Element; SearchTree Left; SearchTree Right; };
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; 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) return NULL; else if(T->Left == NULL) return T; else return FindMin(T->Left); } Position FindMin(SearchTree T) { if(T != NULL) while(T->Left != NULL) T = T->Left; return T; }
Position FindMax(SearchTree T) { if(T == NULL) return NULL; else if(T->Right == NULL) return T; else return FindMax(T->Right); } 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 = (SearchTree)malloc(sizeof(struct TreeNode)); if(T == NULL){ printf("Out of space.\n"); return NULL; } }else if(X < T->Element){ T->Left = Insert(X, T->Left); }else (X > T->Element){ T->Right = Insert(X, T->Right); } return T; }
SearchTree Delete(ElementType X, SearchTree T) { Position TmpCell; if(T == NULL){ fprintf(stderr,"Element not found.\n"); return NULL; }else if(X < T->Element) T->Left = Delete(X, T->Left); else if(X > T->Element) T->Right = Dlelte(X, T->Right); else if(T->Left && T->Right){ TmpCell = FindMin(T->Right); T->Element = TmpCell->Element; T->Right = Delete(T->Element, T->Right); }else{ TmpCell = T; if(T->Left == NULL) T = T->Right; else if(T->Right == NULL) T = T->Left; free(TmpCell); } return T; }
标签:二叉树
原文地址:http://blog.csdn.net/to_be_it_1/article/details/37723577