题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
思路
核心思想:一棵树的最小深度,就是min(左子树的最小深度,右子树的最小深度) + 1.
递归:
- 当根节点左、右子树均为 null 时,这个树的最小深度就是1.
- 当左、右子树都不为 null 时,这个树的最小深度就是min(左子树的最小深度,右子树的最小深度) + 1.
- 当左、右子树有一棵为 null 时,这棵树的最小深度就是那颗非空子树的最小深度 + 1.
复杂度分析
假设树有 n 个节点。
- 时间复杂度O(n),遍历整棵树。
- 空间复杂度O(n),空间复杂度取决二叉树的节点数。
代码
class Solution {
public static int minDepth(TreeNode root) {
if (root == null){
return 0;
}
return minDepthHelper(root);
}
private static int minDepthHelper(TreeNode root) {
if (root.left == null && root.right == null) {
return 1;
} else if (root.left != null && root.right != null) {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
} else if (root.left != null){
return minDepth(root.left) + 1;
}else {
return minDepth(root.right) + 1;
}
}
}