面试算法-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;
    }
}
相关推荐
岁忧20 小时前
(LeetCode 每日一题) 3541. 找到频率最高的元音和辅音 (哈希表)
java·c++·算法·leetcode·go·散列表
pusue_the_sun20 小时前
每日算法题推送
算法·双指针
KyollBM20 小时前
【Luogu】P9809 [SHOI2006] 作业 Homework (根号算法)
算法
jmxwzy20 小时前
leetcode274.H指数
算法
纪元A梦21 小时前
贪心算法应用:信用评分分箱问题详解
java·算法·贪心算法
过河卒_zh15667661 天前
9.13AI简报丨哈佛医学院开源AI模型,Genspark推出AI浏览器
人工智能·算法·microsoft·aigc·算法备案·生成合成类算法备案
D.....l1 天前
冒泡排序与选择排序以及单链表与双链表
数据结构·算法·排序算法
sinat_286945191 天前
Case-Based Reasoning用于RAG
人工智能·算法·chatgpt
Athenaand1 天前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论