Insertion into BST without header Node JAVA

Posted by Petiatil on Stack Overflow See other posts from Stack Overflow or by Petiatil
Published on 2012-10-24T04:44:14Z Indexed on 2012/10/24 5:01 UTC
Read the original article Hit count: 87

Filed under:
|

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;
     }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about binary-search-tree