题目,这几天都是截图来描述题目,因为二叉树不好复制:
我的代码
解释:这道题跟最大深度一样的,使用递归就变得十分简单,唯一不同的就是当两边有一个为0时,需要去深度较大的那个,比如这个测试用例 [1,2]那么结果是2而不是0,因为要求的是到达根节点的最小,右边没有这样就不能以0深度计算了,这点需要注意。。。
public static int minDepth(TreeNode root) {
if(root == null){
return 0;
}else {
int left = minDepth(root.left);
int right = minDepth(root.right);
if(left == 0){
return right + 1;
}else if (right == 0) {
return left + 1;
}else {
return left > right ? right +1 :left + 1;
}
}
排名比较高的代码,我又有点懵逼,跟我的感觉没啥区别啊
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/**
* 空树,最小深度为0
* <p>
* 左右子树都为空,最小深度为1
* <p>
* 左右子树不都为空,左右子树中有空树的情况,最小深度一定是在非空树中产生,因为最小深度定义为到最近叶子节点的深度。一旦左右子树有空的情况,这边的深度就可以置为正无穷,表示最小深度不可能再这里产生。然后分别计算左右子树的最小深度,使用递归策略。
*
* @param root
* @return
*/
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int leftHeight = 1;
int rightHeight = 1;
if (root.left != null) {
leftHeight = minDepth(root.left);
} else {
leftHeight = Integer.MAX_VALUE;
}
if (root.right != null) {
rightHeight = minDepth(root.right);
} else {
rightHeight = Integer.MAX_VALUE;
}
return Math.min(leftHeight, rightHeight) + 1;
}
}