public static int run(TreeNode root) {
if (root==null){
return 0;
}
if(root.left==null){
return run(root.right)+1;
}
if (root.right==null){
return run(root.left)+1;
}
return Min(run(root.left),run(root.right))+1;
}
public static int Min(int x, int y){
if (x>=y){
return y;
}else{
return x;
}
}
递归遍历,每个节点的深度就是左子树和右子树的最小深度+1,并向上一层返回。但是这里有个小细节,就是当左子树空和右子树空需要单独拿出来判断,否则虽然结果正确,但会超时。因为如果不加这个条件,左右子树只要一个为空的就会多调用一次函数,当树的规模较大时,这个差距就很明显了。