0

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 method 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());

1 Answer 1

2

I guess your declaration of E is "E extends Comaprable", in that case when you called nd.getRight it returned TreeNode instance which has to be comparable for the cast to succeed.

The line where the exception occured should look like below for the cast to pass

nd.setItem(nd.getRight.getItem)
Sign up to request clarification or add additional context in comments.

3 Comments

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 && nd.getRight() == null) { nd = null; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.