【问题标题】:Error implementing Level Order Traversal Binary Search Tree with Java PriorityQueue使用 Java PriorityQueue 实现级别顺序遍历二叉搜索树时出错
【发布时间】:2014-11-23 19:44:36
【问题描述】:

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

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

【问题讨论】:

    标签: java binary-search-tree priority-queue tree-traversal


    【解决方案1】:

    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 对象与其他节点具有可比性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2016-07-11
      • 2015-06-23
      • 1970-01-01
      • 2020-12-12
      相关资源
      最近更新 更多