面试算法-73-二叉树的最小深度

题目

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

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

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

示例 1:

输入:root = [3,9,20,null,null,15,7]

输出:2

java 复制代码
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }

        if(root.left == null && root.right == null){
            return 1;
        }

        if(root.left == null){
            return minDepth(root.right) +1;
        }

        if(root.right == null){
            return minDepth(root.left) +1;
        }
        
        return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
    }
}
相关推荐
Jasmine_llq8 小时前
《P3572 [POI 2014] PTA-Little Bird》
算法·滑动窗口·单调队列·动态规划(dp)·多组查询处理·循环优化(宏定义 rep)
tankeven8 小时前
HJ101 排序
c++·算法
流云鹤8 小时前
动态规划02
算法·动态规划
小白菜又菜9 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见4049 小时前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
多恩Stone9 小时前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
踢足球09299 小时前
寒假打卡:2026-2-23
数据结构·算法
田里的水稻9 小时前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z9 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
郝学胜-神的一滴10 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构