J.E.D.I
BSTNode bstHead = new BSTNode; Creates an empty bst
BST{ bstHead.left = bstHead;
bstHead.right = bstHead; }
Creates a bst with root r, pointed to by bstHead.right BSTBSTNode r{
bstHead.left = bstHead; bstHead.right = r;
} }
9.3.1 Searching
In searching for a value, say k, three conditions are possible:
• k =
value at the node successful search • k
value at the node search the left subtree • k
value at the node search the right subtree The same process is repeated until a match is found or the farthest leaf is reached but no
match is found. In the case of the latter, the search is unsuccessful. The following is the Java implementation of the above algorithm:
Searches for k, returns the node containing k if found BSTNode searchint k{
BSTNode p = bstHead.right; the root node If the tree is empty, return null
if p == bstHead return null; Compare
while true{ if k == p.info return p;
successful search else if k p.info
go left if p.left = null p = p.left;
else return null; not found
else go right
if p.right = null p = p.right; else return null;
not found }
}
9.3.2 Insertion
In inserting a value, searching is performed in finding its proper location in the tree. However, if during the search process the key is found, the insertion will not be
performed. The following is the algorithm:
Data Structures 173
J.E.D.I
1. Start the search at the root node. Declare a node p and make it point to the root 2. Do the comparison:
if k == p.info return false if key found, insertion not allowed
else if k p.info p = p.left go left
else p = p.right if k p.info go right
3. Insert the node p now points to the new parent of node to insert: newNode.info = k
newNode.left = null newNode.right = null
if k p.info p.left = newNode else p.right = newNode
In Java, Inserts k into the binary search tree
boolean insertint k{ BSTNode p = bstHead.right; the root node
BSTNode newNode = new BSTNode; If the tree is empty, make the new node the root
if p == bstHead{ newNode.info = k;
bstHead.right = newNode; return true;
} Find the right place to insert k
while true{ if k == p.info
key already exists return false;
else if k p.info go left
if p.left = null p = p.left; else break;
else go right
if p.right = null p = p.right; else break;
} Insert the new key in its proper place
newNode.info = k; if k p.info p.left = newNode;
else p.right = newNode; return true;
}
9.3.3 Deletion