2017-01-22 288 views
0

我想用递归和迭代方法求和二叉树的元素。虽然递归的工作正常,迭代给了我一个例外。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; 
     } 

} 

Queue q = new LinkedList();在MAX2,方法是给我的异常: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: javaapplication34.LinkedList cannot be converted to java.util.Queue

谁能帮助吗?给我一个kickstart或一个小解释?我很不确定详细的问题。

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

+0

你是否自己声明了一个LinkedList类? –

+0

是的,我错过了队列。我现在importet LinkedList,它工作得很好。我的意思是,它的工作。它没有达到我的预期,因为它比我的递归版本提供了另一个总和。 –

回答

3

看来您已经在同一个包中定义了一个名为LinkedList的类,并且它没有实现Queue

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

+0

谢谢。这确实很简单。 –

+0

很高兴听到。如果您发现它有帮助,请不要忘记接受此答案。 –

0

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

LinkedList q = new LinkedList(); 

(我假定它是一个任务,你必须使用这个特殊的LinkedList作为任务)