0

I'm having issues implementing my breadth first traversal for my binary tree. I keep getting a class cast exception at these two lines:

        if(node.left != null) queue.offer(node.left);
        if(node.right != null) queue.offer(node.right);

The exception says: "TreeNode cannot be cast to java.lang.Comparable" I need the extends Comparable for other methods this class, any suggestions on how to fix this? Thanks!

public class TreeNode<E extends Comparable<E>> {

private TreeNode<E> left;
private TreeNode<E> right;
private E value;


public TreeNode(E value) 
{
    this.value = value;
}

    public void breadthFirstTraversal(TreeNode<E> root, ArrayList<E> breadthList)
{
    Queue<TreeNode<E>> queue = new PriorityQueue<TreeNode<E>>();
    if (root == null)
        return;
    queue.clear();
    queue.offer(root);
    while(!queue.isEmpty())
    {
        TreeNode<E> node = queue.remove();
        breadthList.add(node.value);
        if(node.left != null) queue.offer(node.left);
        if(node.right != null) queue.offer(node.right);
    }
}

1 Answer 1

1

You have:

public class TreeNode<E extends Comparable<E>>

This only says that the E in TreeNode<E> should implement Comparable, not that the TreeNode itself should. For that you would need to make TreeNode implement Comparable in the usual fashion:

public class TreeNode<E extends Comparable<E>> implements Comparable<TreeNode<E>> 

And add the appropriate overrides.

Sign up to request clarification or add additional context in comments.

Comments

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.