• 35二叉树-树的最小深度


    目录

    LeetCode之路——111. 二叉树的最小深度

    分析

    解法一:广度优先查询

    解法二:深度优先查询



    LeetCode之路——111. 二叉树的最小深度

    给定一个二叉树,找出其最小深度。

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    说明:叶子节点是指没有子节点的节点。

    示例 1:

    img

    输入: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 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)。

  • 相关阅读:
    媒体服务器与视频服务器有什么区别
    中学化学教学参考杂志社中学化学教学参考编辑部2022年第12期目录
    jwt 实现用户登录完整java
    Mybatis-Plus高级之LambdaQueryWrapper,Wrappers.<实体类>lambdaQuery的使用
    基于SSM的高校餐厅防疫管理系统
    处理器管理
    池化(Pooling)的种类与具体用法——基于Pytorch
    89.(cesium篇)cesium聚合图(自定义图片)
    CSDN 僵尸粉 机器人
    C#winfrom调整任意控件宽和高
  • 原文地址:https://blog.csdn.net/Elaine2391/article/details/134064942