首先给出此ADT的声明:
1 struct TreeNode; 2 typedef struct TreeNode *Position; 3 typedef struct TreeNode *SearchTree; 4 5 SearchTree MakeEmpty(SearchTree T); 6 Position Find(ElementType X, SearchTree T); 7 Position FindMax(SearchTree T); 8 Position FindMin(SearchTree T); 9 SearchTree Insert(ElementType X, SearchTree T); 10 SearchTree Delete(ElementType X, SearchTree T); 11 ElementType Retrieve(Position P); 12 13 struct TreeNode{ 14 ElementType Element; 15 SearchTree Left; 16 SearchTree Right; 17 };
1、MakeEmpty的实现
1 SearchTree MakeEmpty(SearchTree T){ 2 if(T != NULL){ 3 MakeEmpty(T->Left); 4 MakeEmpty(T->Right); 5 free(T); 6 } 7 return NULL; 8 }
2、Find的实现
1 Position Find(ElementType X, SearchTree T){ 2 if(T == NULL) 3 return NULL; 4 else if(X < T->Element) 5 return Find(X, T->Left); 6 else if(X > T->Element) 7 return Find(X, T->Right); 8 else 9 return T; 10 }
3、FindMax和FindMin的实现(一个递归 一个非递归)
Position FindMin(SearchTree T){ if(T == NULL) return NULL; else if(T->Left == NULL) return T; else return FindMin(T->Left); } Position FindMax(SearchTree T){ if(T != NULL) while(T->Right != NULL) T = T->Right; return T; }
4、Insert的实现
1 SearchTree Insert(ElementType X, SearchTree T){ 2 if(T == NULL){ 3 T = (SearchTree)malloc(sizeof(struct TreeNode)); 4 T->Element = X; 5 T->Left = T->Right = NULL; 6 } 7 else if(X < T->Element) 8 T->Left = Insert(X, T->Left); 9 else if(X > T->Element) 10 T->Right = Insert(X, T->Right); 11 12 // Else X is in the tree already, we'll do nothing! 13 return T; 14 }
5、Delete的实现
1 SearchTree Delete(ElementType X, SearchTree T){ 2 Position TmpCell; 3 4 if(T == NULL) 5 printf("Element Not Found "); 6 else if(X < T->Element) 7 T->Left = Delete(X, T->Left); 8 else if(X > T->Element) 9 T->Right = Delete(X, T->Right); 10 else if(T->Left && T->Right){ 11 TmpCell = FindMin(T->Right); 12 T->Element = TmpCell->Element; 13 T->Right = Delete(TmpCell->Element, T->Right); 14 } 15 else{ 16 TmpCell = T; 17 if(!(T->Left)) 18 T = T->Right; 19 else if(!(T->Right)) 20 T = T->Left; 21 free(TmpCell); 22 } 23 return T; 24 }