力扣 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;
    }
}
相关推荐
Univin22 分钟前
C++(10.5)
开发语言·c++·算法
Asmalin38 分钟前
【代码随想录day 35】 力扣 01背包问题 一维
算法·leetcode·职场和发展
剪一朵云爱着41 分钟前
力扣2779. 数组的最大美丽值
算法·leetcode·排序算法
qq_428639611 小时前
虚幻基础:组件间的联动方式
c++·算法·虚幻
深瞳智检1 小时前
YOLO算法原理详解系列 第002期-YOLOv2 算法原理详解
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪
tao3556671 小时前
【Python刷力扣hot100】283. Move Zeroes
开发语言·python·leetcode
怎么没有名字注册了啊2 小时前
C++后台进程
java·c++·算法
Rubisco..2 小时前
codeforces 2.0
算法
未知陨落2 小时前
LeetCode:98.颜色分类
算法·leetcode
~kiss~3 小时前
K-means损失函数-收敛证明
算法·机器学习·kmeans