Reputation: 143
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);
}
}
Upvotes: 0
Views: 414
Reputation: 40315
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.
Upvotes: 1