Data Structures, Algorithms, & Applications in Java
Chapter 15, Exercise 9
The modified code is given below.
public class ModifiedBinarySearchTree extends BinarySearchTree
{
public Object modifiedGet(Object theKey)
{
// pointer p starts at the root and moves through
// the tree looking for an element with key theKey
BinaryTreeNode p = root;
Comparable searchKey = (Comparable) theKey;
while (p != null)
// examine p.element.key
if (searchKey.compareTo(((Data) p.element).key) == 0)
// if correct key is found
{
return ((Data) p.element).element;
}
else if (searchKey.compareTo(((Data) p.element).key) < 0)
{
p = p.leftChild;
}
else
{
p = p.rightChild;
}
// no matching element
return null;
}
}