here is my code:
public int minDepth(TreeNode root) {
int crtDepth = 0;
if (root != null) {
int tmp1 = 1, tmp2 = 1;
tmp1 += minDepth(root.left);
tmp2 += minDepth(root.right);
crtDepth += tmp1 < tmp2 ? tmp1 : tmp2;
}
return crtDepth;
}
not every intermediate node has both left child and right child
If it has no right child, for example, you shouldn't calculate midDepth(root.right)
at all.
public class Solution {
public int minDepth(TreeNode root) {
int crtDepth = 0;
if (root != null) {
if (root.left == null) {
return 1 + minDepth(root.right);
}
else if (root.right == null) {
return 1 + minDepth(root.left);
}
int tmp1 = 1, tmp2 = 1;
tmp1 += minDepth(root.left);
tmp2 += minDepth(root.right);
crtDepth += tmp1 < tmp2 ? tmp1 : tmp2;
}
return crtDepth;
}
}
it didn't solve the question.
Let me give you an example. Suppose an intermediate node has only left child but no right child. The minDepth of the left subtree is 7. Then you should return 8 for this node.
However, since you call minDepth(root.right)
as well and it will return 0 for sure because root.right == null
, you will return 1, which is completely wrong.