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;
    }
}
全部评论

相关推荐

在打卡的大老虎很想潜...:你在找实习,没啥实习经历,技术栈放前面,项目多就分两页写,太紧凑了,项目你最多写两个,讲清楚就行,项目背景。用到的技术栈、亮点、难点如何解决,人工智能进面太难了,需求少。你可以加最新大模型的东西
点赞 评论 收藏
分享
二十岁的编程男神王大...:读博吧兄弟,你这绩点太好了,何必转码,另外哈哈哈真见到有括号标出来985的,这个不标注也知道吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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