|
Functions can take advantage of the ordering requirement in a way that is similar to what binary search does. A membership testing function can exploit the following facts.
An empty tree has no members.
If the root of T contains x, then tree T clearly contains x.
If the root of T contains k and x < k then, if x occurs in T at all, it must occur in T 's left subtree, by the ordering requirement for binary search trees.
Similarly, if the root of T contains k and x > k, then x occurs in T if and only if x occurs in T 's right subtree.
//========================================== // member //========================================== // member(x,T) returns true if x is in binary // search tree T. //========================================== bool member(const int x, const Tree> T) { if(T == NULL) { return false; } else if(x == T->item) { return true; } else if(x < T->item) { return member(x, T->left); } else { return member(x, T->right); } }
Notice the similarity between that and binary search.
To insert a value, just find where that value would have been, had it already been in the tree, then add the value as a new leaf. For example, inserting 13 as shown below would result in the following change.
The actual insertion takes place when a null tree is encountered. The null tree is replaced by a leaf. An immediate consequence is:
If x is inserted into a tree T that does not already contain x, then x is in a leaf after the insertion. |
If the value x to be inserted is already in the tree, nothing is done.
//========================================== // insert //========================================== // insert(x,T) inserts x (destructively) into // binary search tree T. If x is already a // member of T, insert does nothing. //========================================== void insert(int x, Tree& T) { if(T == NULL) { T = new Node(x, NULL, NULL); } else if(x < T->item) { insert(x, T->left); } else if(x > T->item) { insert(x, T->right); } }
Notice that parameter T is passed by reference. The first case needs to change the pointer that is stored in T. Also notice that there is no case for x = T->item since insert is supposed to do nothing when x already occurs in the tree.
What tree do you get if you insert 25 into the following binary search tree?
What tree do you get if you insert 7 into the following binary search tree?
What tree do you get if you insert 11 into the following binary search tree?
|