面试算法-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;
    }
}
相关推荐
wadesir8 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi9878389 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill9 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit9 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung9 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
wifi chicken10 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊10 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino10 小时前
agc011_e 题解
算法
bubiyoushang88811 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab
风筝在晴天搁浅11 小时前
hot100 240.搜索二维矩阵Ⅱ
算法·矩阵