c++ 优先队列_常见二叉树面试题2: 广度优先遍历(BFS)

937352427c23fea0a9637e1a1928c3c3.png

广度优先遍历(Breadth First Search)

面试中,谈到二叉树大家是不是容易紧张,各种红黑树、平衡树、大小堆,不要紧张。今天就开始逐个破解,第2期来讲二叉树的深度优先遍历(BFS)相关知识。

5d882d4f793451bd41f13d0262d5c171.png

二叉树

广度优先遍历(BFS),也称为层次优先遍历,是优先考虑尽可能广的遍历一个树的遍历方式。如上图,广度优先遍历的顺序为:

A-B-C-D-E-D-F-G

广度优先遍历通常会借助一个队列来实现,思路为:

  1. 将root放入队列
  2. 当队列不为空时循环
  3. 在循环中
    1. 取出队首元素
    2. 做一些处理,如输出、求和、存储等
    3. 在存在左节点时,将左节点放入队列
    4. 在存在右节点时,将右节点放入队列

通用的代码模板为:

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); } }}

最后,欢迎大家转发、关注。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值