111. 二叉树的最小深度

题目描述

链接: https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/submissions/

解题思路:

利用递归的思想, 分四种情况:

  • 当前节点空, 返回0
  • 当前节点的左节点飞空, 递归求左子树的最小深度, 返回+1(本身也算一个)
  • 当前节点的右节点飞空, 递归求右子树的最小深度, 返回+1(本身也算一个)
  • 左右节点都空, 返回1

代码:

// T: O(n), S: O(n)
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if ((root.left == null) && (root.right == null)) return 1;
        int min_depth = Integer.MAX_VALUE;
        if (root.left != null) {
            min_depth = Math.min(minDepth(root.left), min_depth);
        }
        if (root.right != null) {
            min_depth = Math.min(minDepth(root.right), min_depth);
        }
        return min_depth + 1;
    }
}
全部评论

相关推荐

这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
07-07 12:47
门头沟学院 Java
码农索隆:竟然还真有卡体检报告的
点赞 评论 收藏
分享
uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务