面试算法-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;
    }
}
相关推荐
小郎君6582 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
邵奈一2 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS1002 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
shehuiyuelaiyuehao2 小时前
算法56,重排链表
数据结构·算法·链表
qq_452396233 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》
算法·哈希算法·gin
西索斯coding3 小时前
Qwen3-Max 与 Qwen-Plus:60 个真实修复任务评测方案
大数据·网络·算法·ai
INGNIGHT4 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划
suhan4 小时前
【数据结构】七、查找:1.查找的概念、线性结构查找(顺序、折半(二分)、插值、稠密、分块、倒排)
数据结构·算法·排序算法
killerbasd4 小时前
总结 10.26
算法