public int maxDepth(TreeNode root) {
if(root==null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
}
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
return Math.min(minDepth(root.left), minDepth(root.right))+1;
}
这种写法看似可以 二叉树【1,2】 在执行minDepth(root.right)返回值为0 哪么min值就为0了 就与minDepth(root.left)无关
正确写法
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
int a = minDepth(root.left);
int b = minDepth(root.right);
if(a==0) return b+1;
else if(b==0) return a+1;
else {
return Math.min(a,b)+1;
}
}