目录
LeetCode之路——111. 二叉树的最小深度
分析
解法一:广度优先查询
解法二:深度优先查询

LeetCode之路——111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:

输入:root = [3,9,20,null,null,15,7] 输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6] 输出:5
提示:
-  树中节点数的范围在 [0, 105]内
-  -1000 <= Node.val <= 1000
分析
还是可以使用层序遍历的思路来处理,最小深度的节点的条件:左右孩子都为空。
解法一:广度优先查询
class Solution {
    public int minDepth(TreeNode root){
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int deep = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            deep++;
            TreeNode cur = null;
            for (int i = 0; i < size; i++) {
                cur = queue.poll();
                //如果当前节点的左右孩子都为空,直接返回最小深度
                if (cur.left == null && cur.right == null){
                    return deep;
                }
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);
            }
        }
        return deep;
    }
} 
-  时间复杂度:O(n) 
-  空间复杂度:O(n) 
解法二:深度优先查询
官网题解:
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int min_depth = Integer.MAX_VALUE;
        if (root.left != null) {
            min_depth = Math.min(minDepth(root.left), min_depth);
        }
        if (root.right != null) {
            min_depth = Math.min(minDepth(root.right), min_depth);
        }
        return min_depth + 1;
    }
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/solutions/382646/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
来源:力扣(LeetCode) 
-  时间复杂度:O(N),其中 N是树的节点数。对每个节点访问一次。 
-  空间复杂度:O(H),其中 H 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为O(logN)。 












![[moeCTF 2023] REV](https://img-blog.csdnimg.cn/be565110c6ad47d59bfe473a7e832081.png)






