I am trying to implement a level order traversal for my BST, but I am getting a weird error. Here is the code:
public void levelOrderTraverseTree(Node focusNode) {
PriorityQueue<Node> currentLevel = new PriorityQueue<Node>();
PriorityQueue<Node> nextLevel = new PriorityQueue<Node>();
currentLevel.add(focusNode);
while (!currentLevel.isEmpty()) {
Iterator<Node> iter = currentLevel.iterator();
while (iter.hasNext()) {
Node currNode = iter.next();
System.out.println(currentLevel.remove());
System.out.println("adding "+currNode.leftChild+"to nextLevel");
nextLevel.add(focusNode.leftChild);
System.out.println("adding "+currNode.rightChild+"to nextLevel");
nextLevel.add(focusNode.rightChild);
}
currentLevel = nextLevel;
nextLevel.clear();
}
}
When I try to run it, I get this error
Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable
on the line that adds focusNode.rightChild
to the nextLevel
queue, or nextLevel.add(focusNode.rightChild);
I am not sure why this error is occurring so any insight would be greatly appreciated.
Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable
means you must implementjava.lang.Comparable
interface in yourNode
class (something like:) for your Node objects to be comparable to other nodes.