Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用队列的Java广度优先搜索_Java - Fatal编程技术网

使用队列的Java广度优先搜索

使用队列的Java广度优先搜索,java,Java,我用Java构建了两个类来遍历广度优先搜索。节点类为: public class Node { Node left; Node right; int value; public Node(int value2) { // TODO Auto-generated constructor stub this.value = value2; } SerachClass中的横向第一搜索方法包括以下code public void breadthFS(Node root) {

我用Java构建了两个类来遍历广度优先搜索。
节点类
为:

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

public Node(int value2) {
// TODO Auto-generated constructor stub
  this.value = value2;
 }
SerachClass
中的横向第一搜索
方法
包括以下
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);
            }
          }

我将感谢你的帮助和评论

您的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);

啊!!。。。非常感谢你,你明白了@Ivan Valerianii如果我的回答解决了你的问题,请标记为正确。那么问题是什么?你只是在这里丢了一些代码,没有解释原因。
if (current.left!=null) bfs.add(current.left);
if (current.right!=null) bfs.add(current.right);