First give the statement of this ADT:
1 structTreeNode;2typedefstructTreeNode *Position;3typedefstructTreeNode *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);Ten searchtree Delete (ElementType X, Searchtree T); One ElementType Retrieve (Position P); A - structtreenode{ - ElementType Element; the Searchtree left; - Searchtree right; -};
1, the realization of 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 implementation
1 Position Find (ElementType X, Searchtree T) {2 if(T = =NULL)3 returnNULL;4 Else if(X < t->Element)5 returnFind (X, t->Left );6 Else if(X > t->Element)7 returnFind (X, t->Right );8 Else9 returnT;Ten}
3, Findmax and findmin implementation (a recursive one non-recursive)
Position findmin (Searchtree T) {if(T = =NULL)returnNULL; Else if(T->left = =NULL)returnT; Else returnFindmin (t->Left );} Position Findmax (Searchtree T) {if(T! =NULL) while(T->right! =NULL) T= t->Right ; returnT;}
4, the implementation of insert
1 searchtree Insert (ElementType X, Searchtree T) {2 if(T = =NULL) {3T = (searchtree)malloc(sizeof(structTreeNode));4T->element =X;5T->left = T->right =NULL;6 }7 Else if(X < t->Element)8T->left = Insert (X, t->Left );9 Else if(X > t->Element)TenT->right = Insert (X, t->Right ); One A //Else X is in the tree already, we 'll do nothing! - returnT; -}
5, delete the implementation
1 searchtree Delete (ElementType X, Searchtree T) {2 Position Tmpcell;3 4 if(T = =NULL)5printf"Element not found\n");6 Else if(X < t->Element)7T->left = Delete (X, t->Left );8 Else if(X > t->Element)9T->right = Delete (X, t->Right );Ten Else if(T->left && t->Right ) { OneTmpcell = Findmin (t->Right ); AT->element = tmpcell->Element; -T->right = Delete (tmpcell->element, t->Right ); - } the Else{ -Tmpcell =T; - if(! (t->Left )) -T = t->Right ; + Else if(! (t->Right )) -T = t->Left ; + Free(Tmpcell); A } at returnT; -}
Binary search Tree Adt--c language description