Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
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||right==0){
return left+right+1;
}else{
return Math.min(left,right)+1;
}
}
}
本题比较简单,用递归思路:
注意,一开始考虑欠佳,忽略了if(left==0||right==0)
的条件判断,导致若某一节点node.left||node.right==0
,minDepth()递归结果会-1,出现错误。