views:

50

answers:

1

Hello All, I have been using a driver to test one of my data structures(Binary Search Tree) and i have come across this issue. -It happens when i insert more than 2 objects into the bst -What I am trying to do: I am inserting 4 objects into the tree, then i am deleting 2 objects, and then printing out my find method so that it displays whether or not it found the objects i request. for instance:

BinarySearchTree2<Integer> theData1 = new BinarySearchTree2<Integer>();
     long start1 = System.currentTimeMillis();  
   theData1.insert(c1);
  theData1.insert(c2);
  theData1.insert(c3);
    theData1.delete(c2);
    System.out.println(theData1.find(c1));
    System.out.println(theData1.find(c2));
    System.out.println(theData1.find(c3));
    System.out.println(theData1.find(c4));

I receive this error when i run it:

Exception in thread "main" java.lang.ClassCastException: TreeNode cannot be cast to java.lang.Comparable at BinarySearchTree2.delete(BinarySearchTree2.java:83) at Driver5.main(Driver5.java:36)

which then points to the delete mehtod in my bst class which is:

public void delete(E item) {

        TreeNode<E> nd = root;

        while(nd != null && nd.getItem().compareTo(item) != 0)
        {
            if(nd.getItem().compareTo(item) < 0)
                nd = nd.getRight();

            else
                 nd = nd.getLeft();
        }

        if( nd.getLeft() == null && nd.getRight() == null)
        {
            nd = null;
        }

        else if(nd.getLeft() != null && nd.getRight() == null)

        {
            nd.setItem((E)nd.getLeft());

        }
        else if(nd.getLeft() == null && nd.getRight() != null)
        {    
            nd.setItem((E)nd.getRight());

        }

        else if(nd.getLeft() != null && nd.getRight() != null)
        {

            nd.setItem((E)findsucc(nd));
        }    

}

the error points directly to this line in my delete method: nd.setItem((E)nd.getRight());

+2  A: 
keshav.veerapaneni
Keshav, You are completely correct... i have been overlooking this small error for an hour and could not figure it out. Thank you so much, makes perfect sense
I now get a null pointer exception as i enter more objects into the BST at
if( nd.getLeft() == null }