1

I'm writing a binary search tree in java with generic classes, but the nodes aren't adding correctly and I can't figure out why.

Here's my insert method (iterative):

public void insert (E element){
    //iterative insert element to tree

    Node<E> node = new Node<>(element); //create new node for element
    Node<E> current = root;

    if (root == null) root = node; // if no root, new node is the root

    else {
        while (current != null){ //traverse tree to get to correct parent node

            if (element.compareTo(current.data) < 0) { //case 1: node is smaller than current
                if (current.left == null){ 
                    node.parent = current;
                    current.left = node;
                }
                else {
                    current = current.left;
                }
            }
            else if (element.compareTo(current.data) > 0) { //case 2: node is larger than current
                if (current.right == null){
                    node.parent = current;
                    current.right = node;
                }
                else {
                    current = current.right;
                }
            }
            else { //case 3: node already exists
                throw new RuntimeException("Node already exists");
            }
        }
    }
    size++;
}

the problem happens when I'm running my test class. there first node is added and becomes the root, but the next insert after that throws the exception no matter what the value is. It's acting like the value I'm trying to add already exists in the tree. If I comment out the exception, the test class doesn't compile, as if it's running an infinite loop.

What am I doing wrong here?

1 Answers1

0

How would current ever become null in your while loop?

You don't break out from your while loop even when you insert new element:

if (current.left == null) { 
  node.parent = current;
  current.left = node;
}

On the next iteration you assign current to the value you just inserted into current.left:

} else {
  current = current.left;
}

and yet on the next iteration you now have current.data equal to element, which leads to the exception. Add break; after you insert the element:

if (current.left == null) { 
  node.parent = current;
  current.left = node;
  break;
}
LeffeBrune
  • 3,441
  • 1
  • 23
  • 36