我正在尝试为我的BST实现一个级别顺序遍历,但我得到一个奇怪的错误。 这是代码:
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();
}
}
当我尝试运行它时,我收到此错误
Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable
focusNode.rightChild
添加到nextLevel
队列,或nextLevel.add(focusNode.rightChild);
的行上的
我不确定为什么会出现这种错误,因此我们将非常感谢任何见解。
答案 0 :(得分:1)
Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable
表示您必须在java.lang.Comparable
课程中实施Node
界面
(如:
public class Node implements Comparable {
//...
})
)使您的Node对象与其他节点相当。