Monday, July 10, 2017

111. Minimum Depth of Binary Tree

二刷
100.00 % 
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int min = 0;
        if (root.left == null && root.right == null) {
            min = 0;
        } else if (root.left == null) {
            min = minDepth(root.right);
        } else if (root.right == null) {
            min = minDepth(root.left);
        } else {
            min = Math.min(minDepth(root.left), minDepth(root.right));
        }
        return min + 1;
    }
}


一刷
看着很简单但是还是有坑的

不能无脑取Min
因为如果 root有一个child是null,另一个child很深,就会返回1但是并不是leaf to root
所以要有一个判断,如果一个child depth是0就要返回另外一个
只有当两个都不是0的时候才取min
16.41 %
public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        if (left == 0) return right + 1;
        if (right == 0) return left + 1;
        return Math.min(left, right) + 1;
    }
}

No comments:

Post a Comment