LeetCode.3.minimum-depth-of-binary-tree

题目:求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

二叉树操作主要还是利用尾递归或者循环遍历这两种思路,进而涉及DFS(主要利用递归或者栈实现)或者BFS(主要利用队列实现)。剩下的只需要按照这些思路即可。

递归5种情况

空树;
没有子树;
只有左/右子树;
有俩子树;

注意:

  1. 结点 node.left

  2. 指针 root->left

第一种:递归版本

1.出口:
0:root==null
2.递:left = run(root.left) //遍历左子树
right = run(root.right)//遍历右子树
3.归:
return left + right + 1 : 左节点或者右节点为null,就不需要比较大小
min(left,right) + 1 : 最小的深度 + 当前的深度

public int run(TreeNode root) {
        if(root == null) return 0;
        int left = run(root.left);
        int right = run(root.right);
        if(left == 0 || right == 0) 
            return left + right + 1;
        return Math.min(left, right) + 1;
    }

第二种:
非递归
思路

BFS标准解法,使用next和count来记录下一层和当前层还剩下的节点数,当前层数layer

1.入队标准:节点不为空,
1.1提前退出条件,当前节点是叶子节点,左右节点都是null,返回layer
1.2left或right不为空,入队一次下一层个数(next)+1
2.出队标准:无,出队一次,当前层(count–)减一
3.更新层数:当前层剩余个 count==0时
count = next; //获取下一层个数
layer++;//遍历下一层,层数加1
next= 0;//复位

public int run(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> q = new LinkedList<>();
        int next = 0;//下一层个数
        int count = 1;//当前剩余个数
        int layer = 1;//当前层数
        q.offer(root);
         
        while(!q.isEmpty()) {
            TreeNode cur = q.poll();
            --count;//每弹出一个数,当前层减一
            if(cur.left == null && cur.right == null) return layer;
            if(cur.left != null) {
                q.offer(cur.left);
                ++next;//每加入一个数,当前层+1
            }
            if(cur.right != null) {
                q.offer(cur.right);
                ++next;
            }
            if(count == 0) {//当前层剩余个数结束时,说明已经遍历结束,进入下一层
                count = next;//获取下一层个数
                next = 0;//复位
                ++layer; //遍历下一层,层数加1    
            }
        }
        return layer;
    }
发布了50 篇原创文章 · 获赞 13 · 访问量 2386

猜你喜欢

转载自blog.csdn.net/endless_Y/article/details/105239638