• 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)。

  • 相关阅读:
    【pen200-lab】10.11.1.39
    stm32f4xx-时钟系统
    《Linux驱动:s3c2440 lcd 驱动分析--终结篇》
    ARM TrustZone技术介绍
    抖音开放平台第三方代小程序开发,一整套流程
    工程水文学试卷
    数据库系统原理与应用教程(042)—— MySQL 查询(五):对查询结果排序
    发版检查list
    【CMake】专用变量 ARGC ARGV ARGN 代表含义
    【Springboot】整合kafka
  • 原文地址:https://blog.csdn.net/Elaine2391/article/details/134064942