0
votes

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

2 Answers

0
votes

Coz ur left is null? Shouldnt it be this.left = insert(item)

But there are other issues in the code as well. I will leave that for you to find out.

0
votes

That's because you're reading a param from a null object right before you do a successful insert. Also your left and right are both null, so I'll leave that for you to figure out, but think about it. You should be inserting new Node(item) instead. And if your function is recursive, then you need to pass in a reference for the current parentNode (root). Here's a skeleton to get you on your way, hopefully you can understand the code.

   private Node<Item> insert(Node traversedNode, Item item)
   {
     if(traversedNode == null)
     {
         // make your life easier and pass item in a constructor
         return new Node(item);
     }
     // Do this iff traversedNode != null, which it is in this block
     int compare = item.compareTo(traversedNode.item);
        ... 
     // Now you check to see if compare < 0 and compare > 0
     // then you insert your node accordingly and recursively
     // you need to pass the current node left or right as your new traversedNode
     // eg. traversedNode.left = insert( traversedNode.left, item )
   }