找二叉树深度的最小值。和求树高差不多,注意的是递归中不能和求树高一样直接返回两个子树的最小值,因为如果一个节点只有一个子树求两边的最小值会出错,所以需要判断下。
public int minDepth(TreeNode root) {
if(root==null) return 0;
else{
if(root.right==null) return minDepth(root.left)+1;
if(root.left==null) return minDepth(root.right)+1;
return Math.min(minDepth(root.right)+1,minDepth(root.left)+1);
}
}