2016-03-21 6 views
1

Javaで2つのクラスを構築して、幅優先検索をトラバースしました。 Node classとおりJava Breadth Queueを使用した最初の検索

public class Node { 
    Node left; 
    Node right; 
    int value; 

public Node(int value2) { 
// TODO Auto-generated constructor stub 
    this.value = value2; 
} 

SerachClassでBreadthFirst検索methodは、その後、次code

public void breadthFS(Node root) { 
    // TODO Auto-generated method stub 

      Queue<Node> bfs=new LinkedList<Node>(); 

      if (root==null) 
      { 
       return; 
      } 
      else 
      { 
       bfs.clear(); 
       bfs.add(root); 
       while(!bfs.isEmpty()) 
       { 
        Node current=bfs.remove(); 
        System.out.println("The breadth first search"+current.value); 
        } 
        if (root.left!=null) bfs.add(root.left); 
        if (root.right!=null) bfs.add(root.right); 
      } 
      } 

含み、Iは、挿入した以下の値{6,2,1,3,10,9,11 }。出力は次のようなループになります。

The breadth first search 6 
The breadth first search 2 
The breadth first search 6 
The breadth first search 2 
The breadth first search 6 
... 

あなたのご意見とご感想をお寄せいただきありがとうございます。

+0

だから、問題は何ですか?理由を説明することなくここにいくつかのコードをダンプしました。 – ryanyuyu

答えて

3

間違いがあなたのwhileループにあります:

いうより:

if (root.left!=null) bfs.add(root.left); 
if (root.right!=null) bfs.add(root.right); 

は次のようになります。

if (current.left!=null) bfs.add(current.left); 
if (current.right!=null) bfs.add(current.right); 
+0

Opps !! ...ありがとうございました。 @イワン・ヴァレリアーニ –

+0

私の答えがあなたの問題を解決した場合は、それを正しいものとしてマークしてください。 –

関連する問題