题目地址:
https://leetcode.com/problems/minimum-depth-of-binary-tree/
求根节点到诸多叶子节点的距离中最短的那个。分治法。只需要注意,如果某棵子树的minDepth是 0 0 0,意味着这个子树是null,所以并不存在这课子树的树根到它的叶子节点的路径,当然就不存在最短距离,需要排除。代码如下:
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (left == 0 || right == 0) {
return left + right + 1;
} else {
return Math.min(left, right) + 1;
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。算法正确性可以由数学归纳法得到。
也可以这么写:
public class Solution {
public int minDepth(TreeNode root) {
// 如果是空树,返回0
if (root == null) {
return 0;
}
// 初始化res为无穷大,然后尝试更新它
int res = Integer.MAX_VALUE;
// 如果左子树不为空,统计一下左子树高度
if (root.left != null) {
res = Math.min(res, minDepth(root.left));
}
// 如果右子树不为空,统计一下右子树高度
if (root.right != null) {
res = Math.min(res, minDepth(root.right));
}
// 如果res没被更新,说明左右子树都为空
//(否则左右子树高度至少是1,res必会更新),此时返回1,否则返回res+1
return res == Integer.MAX_VALUE ? 1 : res + 1;
}
}
时空复杂度一样。