2017-01-22 3 views
0

私は、再帰的および反復的な方法でバイナリツリーの要素を合計しようとしています。再帰的なものがfindeで動作する間、反復は私に例外を与えます。 は誰もがここで助けてもらえException in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: javaapplication34.LinkedList cannot be converted to java.util.QueueJavaでのバイナリツリーの要約

:MAX2-方法で

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();は私に例外を与えていますか?私にキックスタートや小さな説明を教えてください。私は非常に問題が何であるかについては確信していません。

私はここにすべてのクラスを追加しませんでした。そのほとんどは共通しているからです。しかし、必要ならば私はそれらを追加します。

+0

自分でLinkedListクラスを宣言しましたか? –

+0

はい、私はそれを行い、キューを見逃しました。私は今LinkedListをインポートし、それは正常に動作します。つまり、うまくいきます。それは私の再帰的なバージョンよりも別の合計を与えるので、私が期待したことをしません。 –

答えて

3

同じパッケージ内にLinkedListというクラスを定義しているように見えますが、Queueは実装されていません。

java.util.LinkedListを使用する場合は、修飾名全体をインポートまたは使用する必要があります。

+0

ありがとうございます。それは本当に簡単でした。 –

+0

聞いて幸いです。それが役に立つとわかったら、この回答を受け入れることを忘れないでください。 –

0

我々は、特別なあなたの実装を知っているLinkedListクラス(それがjava.lang.Queueインタフェースを実装していないだけということ)、しかし、あなただけ言うならば、それはまだ動作するかもしれません。

LinkedList q = new LinkedList(); 

(私はそれと仮定あなたはこの課題にLinkedListを使用する必要があります。

関連する問題