[JAVA] This code is failing some test cases


  • 0
    K
    public static int minDepth(TreeNode root){
            int minDepth = 0;
            if(root != null){
                int md1 =  minDepth(root.left)+1;
                int md2 =  minDepth(root.right)+1;
                if(md1<=md2){
                    minDepth = md1;
                }
                else
                    minDepth = md2;
            }
            
            
            return minDepth;
        }

  • 0
    C

    there is a case that the node only has one child, when this happened the only child should be counted as the minimum depth instead of using 0 for that missing child. (missing child is not a leaf node)


  • 0
    K

    Thanks. this worked!


  • 0
    F

    if a node just has one child, the result is error!
    if left is null and right is null, the root depth is 1;
    if left is null or right is null, the root depth is 2;
    if left is not null and right is not null, return the min(left,right)

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        if (left == 0 && right == 0) return 1;
        if (left == 0 || right == 0) return left > right ? left +1 : right +1;
        return left > right ? right + 1 : left + 1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.