力扣 LeetCode 111. 二叉树的最小深度(Day7:二叉树)

解题思路:

用后序遍历

题目要求的最小深度为根节点到叶子节点的最小深度,注意是到根节点,所以如图所示假设(没有9这个节点)是需要返回3的,而不是1(根节点左子树为空的情况),于是需要加两层判断

其余部分可参考求最大深度的思路,有一定相似之处

java 复制代码
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null && root.right != null) return 1 + rightDepth;
        if (root.left != null && root.right == null) return 1 + leftDepth;
        int res = 1 + Math.min(leftDepth, rightDepth);
        return res;
    }
}
相关推荐
我是苏苏4 小时前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#
sali-tec5 小时前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
黑岚樱梦9 小时前
代码随想录打卡day23:435.无重叠区间
算法
Kuo-Teng9 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
gihigo199810 小时前
MATLAB使用遗传算法解决车间资源分配动态调度问题
算法·matlab
墨染点香10 小时前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
却道天凉_好个秋10 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与11 小时前
算法24.0
算法
晓北斗NorSnow11 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习