繁体   English   中英

使用Java PriorityQueue实现级别顺序遍历二进制搜索树时出错

[英]Error implementing Level Order Traversal Binary Search Tree with Java PriorityQueue

我正在尝试为我的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);

我不确定为什么会发生此错误,因此不胜感激。

Exception in thread "main" java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable意味着您必须在Node类中实现java.lang.Comparable接口(类似:

public class Node implements Comparable {
    //...
})

),以使您的Node对象与其他节点具有可比性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM