![937352427c23fea0a9637e1a1928c3c3.png](https://img-blog.csdnimg.cn/img_convert/937352427c23fea0a9637e1a1928c3c3.png)
广度优先遍历(Breadth First Search)
面试中,谈到二叉树大家是不是容易紧张,各种红黑树、平衡树、大小堆,不要紧张。今天就开始逐个破解,第2期来讲二叉树的深度优先遍历(BFS)相关知识。
![5d882d4f793451bd41f13d0262d5c171.png](https://img-blog.csdnimg.cn/img_convert/5d882d4f793451bd41f13d0262d5c171.png)
二叉树
广度优先遍历(BFS),也称为层次优先遍历,是优先考虑尽可能广的遍历一个树的遍历方式。如上图,广度优先遍历的顺序为:
A-B-C-D-E-D-F-G
广度优先遍历通常会借助一个队列来实现,思路为:
- 将root放入队列
- 当队列不为空时循环
- 在循环中
- 取出队首元素
- 做一些处理,如输出、求和、存储等
- 在存在左节点时,将左节点放入队列
- 在存在右节点时,将右节点放入队列
通用的代码模板为:
bfs(Node root) { if(root == null) return; Queue queue = new LinkedList(); // 增加root节点到队列中 queue.add(root); while (queue.size() > 0) { // 取出队头的元素 Node current = queue.poll(); // 做节点值输出 doSemething(); // 依次处理左右节点 if(current.left != null) queue.add(current.left); if(current.right != null) queue.add(current.right); }}
完整代码为:
class Node{ Node left; Node right; String value; public Node(String value) { this.value = value; }}public class BFS { public static void main(String[] args) { // 构造二叉树 Node a = new Node("A"); Node b = new Node("B"); Node c = new Node("C"); Node d = new Node("D"); Node e = new Node("E"); Node f = new Node("F"); Node g = new Node("G"); a.left = b; a.right = c; b.left = d; b.right = e; c.left = f; c.right = g; // 广度优先遍历 bfs(a); } public static void bfs(Node root) { Queue queue = new LinkedList(); // 增加root节点到队列中 queue.add(root); while (queue.size() > 0) { Node current = queue.poll(); // 做节点值输出 System.out.println(current.value); // 依次处理左右节点 if(current.left != null) queue.add(current.left); if(current.right != null) queue.add(current.right); } }}
最后,欢迎大家转发、关注。