My partner and I are implementing a Binary Search Tree for a Data Structures & Algorithms course. We are encountering issues with our add method. This code is shown below:
public class BinarySearchTree<Type extends Comparable<? super Type>> implements SortedSet<Type>
{
BinaryNode<Type> thisRoot;
/**
* Constructor for this BinarySearchTree
*/
public BinarySearchTree()
{
thisRoot = null;
}
/**
* Adds the specified item to this BinarySearchTree, if it is
* not already contained in this BinarySearchTree.
*
* @param Type item
*
* @return boolean
*/
public boolean add(Type item) {
// If the specified item is null, throw an exception.
if(item == null)
throw new NullPointerException();
// Otherwise, add the item.
return addItem(item, thisRoot);
}
private boolean addItem(Type item, BinaryNode<Type> thisRoot)
{
// Base case - check if thisRoot is null. If it is null,
// we have reached the base case where the item is not contained
// in this BinarySearchTree. Insert the item.
if(thisRoot == null)
{
thisRoot = new BinaryNode<Type>(item);
return true;
}
// Reduction step - recursively call the helper method until the
// specified item is found or added.
// If the item is less than the data in thisNode, then go to
// the left in this BinarySearchTree.
if(item.compareTo(thisRoot.getData()) < 0)
return addItem(item, thisRoot.getLeft());
// If the item is greater than the data in thisNode, then go
// to the right in this BinarySearchTree.
else if (item.compareTo(thisRoot.getData()) > 0)
return addItem(item, thisRoot.getRight());
else
// Item is already contained in this BinarySearchTree.
return false;
}
In our test case, we aren't getting the outcome that we expected. We initially created an empty BinarySearchTree and called on the add method. From here we passed an Integer object (10) to the method. After doing this, the recursive addItem method should have been invoked. thisRoot should currently refer to null (as we created an empty BinarySearchTree) and thus thisRoot should now refer to the new BinaryNode object. However, 10 is not contained in the BST after the method call. thisRoot still points to null. If anyone has any suggestions or insight as to why this might be, we would greatly appreciate it.