使用队列的Java广度优先搜索
我用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) {
节点类
为:
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);