结构体声明:
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); } }
查找操作:
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); else return T; }
FindMin实现:
Position FindMin(SearchTree T) { if (T==NULL) return NULL; else if (T->Left==NULL) return T; else return FindMin(T->Left); }
FindMax实现:
Position FindMax(SearchTree T) { if (T!=NULL) while(T->Right!=NULL) T=T->Right; return T; }
Insert操作:
SearchTree Insert(ElementType X, SearchTree T) { if (T==NULL) { T = malloc(sizeof(struct TreeNode)); if (T==NULL) { FataError("out of space"); } else { T->Element = X; T->Left = T->Right = NULL; } } else if (X<T->Element) T->Left = Insert(X, T->Left); else if (X>T->Element) T->Right = Insert(X, T->Right); return T; }
Delete操作:
1 SearchTree Delete(ElementType X, SearchTree T) 2 { 3 Position TmpCell; 4 if (T==NULL) 5 { 6 Error("Element not found"); 7 } 8 else if (X<T->Element) 9 T->Left = Delete(X, T->Left); 10 else if (X>T->Element) 11 T->Right = Delete(X, T->Right); 12 else if (T->Left && T->Right) 13 { 14 TmpCell = FineMin(T->Right); 15 T->Element = TmpCell->Element; 16 T->Right = Delete(T->Element, T->Right); 17 } 18 else 19 { 20 TmpCell = T; 21 if (T->Left==NULL); 22 T= T->Right; 23 else if (T->Right==NULL); 24 T= T->Left; 25 free(TmpCell); 26 } 27 return T; 28 }