美文网首页
111. Minimum Depth of Binary Tre

111. Minimum Depth of Binary Tre

作者: 7ccc099f4608 | 来源:发表于2020-03-16 13:34 被阅读0次

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

image.png

(图片来源https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

日期 是否一次通过 comment
2020-03-15 0

NOTE: [1,2] ,返回2


image.png

递归

public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }

        int leftD = minDepth(root.left);
        int rightD = minDepth(root.right);

        // 防止corner case: [1,2], 返回应该是2,而不是1,所以需要leftD+rightD+1
        return (leftD == 0 || rightD == 0) ? leftD+rightD+1 : Math.min(leftD, rightD) + 1;
    }

相关文章

网友评论

      本文标题:111. Minimum Depth of Binary Tre

      本文链接:https://www.haomeiwen.com/subject/cmdgehtx.html