Breadth First Search,广度优先搜索。
一般用于找最短路径,时间复杂度较低,代价是空间复杂度高。

框架

想象为一棵树从根节点到全部第二节点再到全部第三节点最后到全部根节点遍历。

  1. // 计算从起点 start 到终点 target 的最近距离
  2. int BFS(Node start, Node target) {
  3. Queue<Node> q; // 核心数据结构
  4. Set<Node> visited; // 避免走回头路
  5. q.offer(start); // 将起点加入队列
  6. visited.add(start);
  7. int step = 0; // 记录扩散的步数
  8. while (q not empty) {
  9. int sz = q.size();
  10. /* 将当前队列中的所有节点向四周扩散 */
  11. for (int i = 0; i < sz; i++) {
  12. Node cur = q.poll();
  13. /* 划重点:这里判断是否到达终点 */
  14. if (cur is target)
  15. return step;
  16. /* cur 的相邻节点加入队列 */
  17. for (Node x : cur.adj())
  18. if (x not in visited) {
  19. q.offer(x);
  20. visited.add(x);
  21. }
  22. }
  23. /* 划重点:更新步数在这里 */
  24. step++;
  25. }
  26. }

队列 q 就不说了,BFS 的核心数据结构;cur.adj() 泛指 cur 相邻的节点,比如说二维数组中,cur 上下左右四面的位置就是相邻节点;visited 的主要作用是防止走回头路,大部分时候都是必须的,但是像一般的二叉树结构,没有子节点到父节点的指针,不会走回头路就不需要 visited。

二叉树的最小高度

Leetcode-简单
image.png
套用上面的框架,start 起点就是根节点root ,重点 target 就是最靠近根节点的叶子节点,也就是叶子节点的两个子节点都为null
表达式为:

  1. if (no.left == null && no.right == null) {
  2. return dep;
  3. }

代码:

  1. public class BFSdemo {
  2. static int bfs(TreeNode root) {
  3. if (root == null) {
  4. return 0;
  5. }
  6. //队列,存储当前层级所有节点
  7. Queue<TreeNode> queue = new LinkedList<>();
  8. queue.add(root);
  9. int dep = 1;
  10. while (!queue.isEmpty()) {
  11. //当前队列大小必须独立常量出来,否则queue.size()的数值不断变化,for循环出错。
  12. int size = queue.size();
  13. for (int i = 0; i < size; i++) {
  14. //获得队列第一个值并移除
  15. TreeNode cur = queue.poll();
  16. //结束条件
  17. if (cur.left == null && cur.right == null) {
  18. return dep;
  19. }
  20. //将cur节点的子节点加入队列
  21. if (cur.left != null) {
  22. queue.offer(cur.left);
  23. }
  24. if (cur.right != null) {
  25. queue.offer(cur.right);
  26. }
  27. }
  28. dep++;
  29. }
  30. return dep;
  31. }
  32. //[3,9,20,null,null,15,7]
  33. public static void main(String[] args) {
  34. TreeNode root = new TreeNode(3);
  35. root.left = new TreeNode(9);
  36. root.right = new TreeNode(20);
  37. root.right.left = new TreeNode(15);
  38. root.right.right = new TreeNode(7);
  39. int dep = bfs(root);
  40. System.out.println(dep);
  41. }
  42. }
  43. public class TreeNode {
  44. public int val;
  45. public TreeNode left;
  46. public TreeNode right;
  47. public TreeNode() {}
  48. public TreeNode(int val) { this.val = val; }
  49. public TreeNode(int val, TreeNode left, TreeNode right) {
  50. this.val = val;
  51. this.left = left;
  52. this.right = right;
  53. }
  54. }