如何实现广度优先遍历?

39

这就是我拥有的内容。我以为前序遍历和深度优先搜索一样,把它们混淆了!

import java.util.LinkedList;
import java.util.Queue;

public class Exercise25_1 {
  public static void main(String[] args) {

    BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 });

    System.out.print("\nInorder: ");
    tree.inorder();
    System.out.print("\nPreorder: ");
    tree.preorder();
    System.out.print("\nPostorder: ");
    tree.postorder();

    //call the breadth method to test it

    System.out.print("\nBreadthFirst:");
    tree.breadth();

  }
}

class BinaryTree {
  private TreeNode root;


  /** Create a default binary tree */
  public BinaryTree() {
  }

  /** Create a binary tree from an array of objects */
  public BinaryTree(Object[] objects) {
    for (int i = 0; i < objects.length; i++) {
      insert(objects[i]);
    }
  }

  /** Search element o in this binary tree */
  public boolean search(Object o) {
    return search(o, root);
  }

  public boolean search(Object o, TreeNode root) {
    if (root == null) {
      return false;
    }
    if (root.element.equals(o)) {
      return true;
    }
    else {
      return search(o, root.left) || search(o, root.right);
    }
  }

  /** Return the number of nodes in this binary tree */
  public int size() {
    return size(root);
  }

  public int size(TreeNode root) {
    if (root == null) {
      return 0;
    }
    else {
      return 1 + size(root.left) + size(root.right);
    }
  }

  /** Return the depth of this binary tree. Depth is the
  * number of the nodes in the longest path of the tree */
  public int depth() {
    return depth(root);
  }

  public int depth(TreeNode root) {
    if (root == null) {
      return 0;
    }
    else {
      return 1 + Math.max(depth(root.left), depth(root.right));
    }
  }

  /** Insert element o into the binary tree
  * Return true if the element is inserted successfully */
  public boolean insert(Object o) {
    if (root == null) {
      root = new TreeNode(o); // Create a new root
    }
    else {
      // Locate the parent node
      TreeNode parent = null;
      TreeNode current = root;
      while (current != null) {
        if (((Comparable)o).compareTo(current.element) < 0) {
          parent = current;
          current = current.left;
        }
        else if (((Comparable)o).compareTo(current.element) > 0) {
          parent = current;
          current = current.right;
        }
        else {
          return false; // Duplicate node not inserted
        }
      }

      // Create the new node and attach it to the parent node
      if (((Comparable)o).compareTo(parent.element) < 0) {
        parent.left = new TreeNode(o);
      }
      else {
        parent.right = new TreeNode(o);
      }
    }

    return true; // Element inserted
  }

  public void breadth() {
  breadth(root);
  }

//  Implement this method to produce a breadth first

//  search traversal
  public void breadth(TreeNode root){
      if (root == null)
          return;

      System.out.print(root.element + " ");
      breadth(root.left);
      breadth(root.right);
 }


  /** Inorder traversal */
  public void inorder() {
    inorder(root);
  }

  /** Inorder traversal from a subtree */
  private void inorder(TreeNode root) {
    if (root == null) {
      return;
    }
    inorder(root.left);
    System.out.print(root.element + " ");
    inorder(root.right);
  }

  /** Postorder traversal */
  public void postorder() {
    postorder(root);
  }

  /** Postorder traversal from a subtree */
  private void postorder(TreeNode root) {
    if (root == null) {
      return;
    }
    postorder(root.left);
    postorder(root.right);
    System.out.print(root.element + " ");
  }

  /** Preorder traversal */
  public void preorder() {
    preorder(root);
  }

  /** Preorder traversal from a subtree */
  private void preorder(TreeNode root) {
    if (root == null) {
      return;
    }
    System.out.print(root.element + " ");
    preorder(root.left);
    preorder(root.right);

  }

  /** Inner class tree node */
  private class TreeNode {
    Object element;
    TreeNode left;
    TreeNode right;

    public TreeNode(Object o) {
      element = o;
    }
  }

}

4
你可以更具体地说明你想要什么,如果你不是在寻找答案的话? - Pops
1
我找不到如何在我的书中进行广度优先遍历的方法...这只是练习,不是作业。请指点一下方向... - not looking for answer
10个回答

116

广度优先搜索

Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
    if (root == null)
        return;
    queue.clear();
    queue.add(root);
    while(!queue.isEmpty()){
        TreeNode node = queue.remove();
        System.out.print(node.element + " ");
        if(node.left != null) queue.add(node.left);
        if(node.right != null) queue.add(node.right);
    }

}

28
为什么队列要在方法外声明?如果同时调用breadth()两次,这将会失败。我看不出把它作为局部变量放在内部有什么缺点。 - Bryan
1
在并发调用 breadth() 的情况下,只有一个队列,因此它将会被添加两次元素,并且随机地被两个调用中的任意一个拉出来,更不用说 LinkedList 不是线程安全的事实了。 - Bryan

50

广度优先搜索使用队列,深度优先搜索使用栈。

对于广度优先搜索,将所有子节点添加到队列中,然后取出头部进行广度优先搜索,再使用相同的队列。

对于深度优先搜索,将所有子节点添加到栈中,然后弹出并对该节点进行深度优先搜索,再使用相同的栈。


6
请看此链接的示例:http://edgblog.wordpress.com/2007/11/28/binary-tree-traversal/ - Subhrajyoti Majumder
1
LaValle(http://planning.cs.uiuc.edu/ch2.pdf),第2.2节提供了BFS,DFS以及其他搜索方法的优秀统一处理。 - 0 _

10

看起来您并不是在要求实现,所以我尝试解释一下这个过程。

使用队列。将根节点添加到队列中。运行循环,直到队列为空。在循环内部,弹出第一个元素并打印出来。然后将其所有子项添加到队列的末尾(通常从左到右)。

当队列为空时,每个元素都应已被打印出。

此外,在维基百科上有关于广度优先搜索的很好的解释:http://en.wikipedia.org/wiki/Breadth-first_search


8
public void breadthFirstSearch(Node root, Consumer<String> c) {
    List<Node> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()) {
        Node n = queue.remove(0);
        c.accept(n.value);

        if (n.left != null)
            queue.add(n.left);
        if (n.right != null)
            queue.add(n.right);
    }
}

同时,Node:

public static class Node {
    String value;
    Node left;
    Node right;

    public Node(final String value, final Node left, final Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

4
//traverse
public void traverse()
{
    if(node == null)
        System.out.println("Empty tree");
    else
    {
        Queue<Node> q= new LinkedList<Node>();
        q.add(node);
        while(q.peek() != null)
        {
            Node temp = q.remove();
            System.out.println(temp.getData());
            if(temp.left != null)
                q.add(temp.left);
            if(temp.right != null)
                q.add(temp.right);
        }
    }
}

}


1

1

您编写的代码不能正确生成BFS遍历结果:(这段代码您声称是BFS,但实际上是DFS!)

//  search traversal
  public void breadth(TreeNode root){
      if (root == null)
          return;

      System.out.print(root.element + " ");
      breadth(root.left);
      breadth(root.right);
 }

2
这是深度优先遍历(先序遍历)。 - Kreisquadratur
1
@Kreisquadratur,你有没有看到我在代码上面的评论?我指的是“你的代码,我复制下来的不是BFS”。 没有人提到过。 但这个代码不是BFS,它是DFS。(我更新了一些内容以使其更加清晰) - Hengameh
1
@Kreisquadratur 没关系,是我错了 :) (请收回你的踩) - Hengameh

0
以下是使用Java 8语法实现的二叉树BFS简单实现。
void bfsTraverse(Node node, Queue<Node> tq) {
    if (node == null) {
        return;
    }
    System.out.print(" " + node.value);
    Optional.ofNullable(node.left).ifPresent(tq::add);
    Optional.ofNullable(node.right).ifPresent(tq::add);
    bfsTraverse(tq.poll(), tq);
}

然后使用根节点和Java队列实现调用此函数

bfsTraverse(root, new LinkedList<>());

即使它是常规树,如果不仅有左右节点,可以使用以下行代替。
Optional.ofNullable(node.getChildern()).ifPresent(tq::addAll);

0

使用以下算法进行广度优先搜索遍历-

  1. 首先使用put方法将根节点添加到队列中。
  2. 在队列不为空的情况下进行迭代。
  3. 获取队列中的第一个节点,然后打印其值。
  4. 将左右子节点(如果当前节点有子节点)添加到队列中。
  5. 完成。我们将按层级逐个打印每个节点的值,通过弹出/删除元素实现。

以下是代码-

    Queue<TreeNode> queue= new LinkedList<>();
    private void breadthWiseTraversal(TreeNode root) {
        if(root==null){
            return;
        }
        TreeNode temp = root;
        queue.clear();
        ((LinkedList<TreeNode>) queue).add(temp);
        while(!queue.isEmpty()){
            TreeNode ref= queue.remove();
            System.out.print(ref.data+" ");
            if(ref.left!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.left);
            }
            if(ref.right!=null) {
                ((LinkedList<TreeNode>) queue).add(ref.right);
            }
        }
    }

-3
public static boolean BFS(ListNode n, int x){
        if(n==null){
           return false;
       }
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>(); 
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
    return true;
}
while(tmp != null){
    for(ListNode<Integer> child: n.getChildren()){
        if(child.val == x){
            return true;
        }
        q.enqueue(child);
    }

    tmp = q.dequeue();
}
return false;
}

我认为在这里根本不需要队列。 - user2133061

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接