Java 中二叉树的求和元素

Summing elements of binary tree in Java

我正在尝试使用递归和迭代方法对二叉树的元素求和。虽然递归的有效,但迭代给了我一个例外。

import java.util.Queue;

public class BinTree {

    public BinNode root;

    public boolean insertNode(BinNode bn) {
        BinNode child=null, parent=null;

        // Knoten suchen, nach welchem eingefuegt wird
        child = root;
        while( child != null) {
            parent = child;
            if (bn.element == child.element)     return false;
            else if (bn.element < child.element) child = child.left;
            else                                 child = child.right;
        }

        // Baum leer?
        if (parent==null)                     root = bn;
        // Einfuegen nach parent, links
        else if (bn.element < parent.element) parent.left = bn;
        // Einfuegen nach parent, rechts
        else                                  parent.right = bn;

        return true;
    }

    public BinNode findNode(int value) {
        BinNode  n = root;

        while (n != null) {
            if (value == n.element)     { return n;    }
            else if (value < n.element) { n = n.left;  }
            else                        { n = n.right; }
        }
        return null;
    }

    public String toString() {
        return root.toString();
    }

        //Max des Gesamtbaumes
        public int max(){
            if(root==null){
                return 0;
            }
            else {
                return root.max();
            }
        }

        //(Iterativ)
        public int max2(){
            //The line that throws out the exception
            Queue q = new LinkedList();
            int sum = 0;
            if(root!=null){
                q.add(root);
            }
            while(!q.isEmpty()){
                BinNode node = (BinNode) q.remove();

                if(node.left == null && node.right == null){
                    sum = sum + node.element;
                }
                else{
                    if(node.left != null){
                        q.add(node.left);
                    }
                }
                if(node.right != null){
                    q.add(node.right);
                }
            }
            return sum;
        }

}

max2-Method 中的 Queue q = new LinkedList(); 给出了异常: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: javaapplication34.LinkedList cannot be converted to java.util.Queue

有人可以帮忙吗?给我一个启动或一点解释?我非常不确定具体是什么问题。

我没有在这里添加每个 class,因为它们中的大多数都很常见。但如果需要,我会添加它们。

您似乎在同一个包中定义了一个名为 LinkedList 的 class,但它没有实现 Queue

如果您想使用 java.util.LinkedList,您应该导入或使用整个限定名称。

我们不知道你的特殊 LinkedList class 的实现(只是它没有实现 java.lang.Queue 接口),但如果你只是说它可能已经工作了:

LinkedList q = new LinkedList();

(我假设这是一个作业,你必须使用这个特殊的 LinkedList 来完成任务)