My simple Java recursive solution

  • 1
        public int minDepth(TreeNode root) {
        if( root == null ) return 0;
        if( root.left == null && root.right == null ) return 1;
        int a = minDepth( root.left );
        int b = minDepth( root.right );
        if( a > 0 && b > 0 ) return Math.min(a,b)+1;
        return a + b + 1;

    My first code was wrong because I didn't aware of if return value is '0', then I should not use it to compare return value from left/right in Math.min, because that way you will always have 0 as minimum, 0 means we already reach the leaf's left or right. We should not consider it as the path end. What I am saying is this is wrong

    return Math.min( minDepth(root.left),minDepth(root.right) ) + 1;

    for finding max depth, this should work well I think.

  • 1

    very good and concise code!
    but it has to traverse all the nodes in the tree, so it may not the most efficient method...

Log in to reply

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