在Java中求和二叉树的元素

时间:2017-01-22 21:48:56

标签: java binary-tree

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

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

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

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

LinkedList q = new LinkedList();

(我认为这是一项任务,你必须使用这个特殊的LinkedList来完成任务)

相关问题