111. Minimum Depth of Binary Tre

2020-03-16  本文已影响0人  7ccc099f4608

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;
    }
上一篇 下一篇

猜你喜欢

热点阅读