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

相关推荐

03-12 14:52
已编辑
长沙学院 Java
点赞 评论 收藏
分享
03-23 15:00
已编辑
厦门大学 Java
xiaowl:你这个简历的问题是对于技术点、项目的描述,都是描述action的,对于面试官而言,仅能知道你干了什么,无法判断你为什么这么干,干的好不好。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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