Insertion into BST without header Node JAVA
- by Petiatil
I am working on a recursive insertion method for a BST. This function is suppose to be a recursive helper method and is in a private class called Node. The Node class is in a class called BinarySearchTree which contains an instance variable for the root.
When I am trying to insert an element, I get a NullPointerException at :
this.left = insert(((Node)left).element);
I am unsure about why this occurs. If I understand correctly, in a BST, I am suppose to insert the item at the last spot on the path transversed. Any help is appreciated!
private class Node implements BinaryNode<E>
{
E item;
BinaryNode<E> left, right;
public BinaryNode<E> insert(E item)
{
int compare = item.compareTo(((Node)root).item);
if(root == null)
{
root = new Node();
((Node)root).item = item;
}
else if(compare < 0)
{
this.left = insert(((Node)left).item);
}
else if(compare > 0)
{
this.right = insert(((Node)right).item);
}
return root;
}
}