思路:后序遍历左右中,但与最大深度细节上有大不同:
1、左右有一个为空时,取不为空的最小高度
2、都不为空时,对比左右深度取最小;
3、都为空时取0,可忽略;
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int ans = 1;
int leftDep = minDepth(root.left); //左
int rightDep = minDepth(root.right); //右
//中,左右有一个为空,取不为空的一边的最小高度
if(root.left==null && root.right!=null) {
ans += rightDep;
}
if(root.left != null && root.right == null) {
ans += leftDep;
}
//都为空时是0,都不为空时,取最小深度
ans += Math.min(leftDep, rightDep);
return ans;
}
}