树与图简单2 种解法
#111二叉树的最小深度
计算根节点到最近叶子节点的节点数。
#二叉树#深度优先搜索#广度优先搜索
原题
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6] 输出:5
提示:
- 树中节点数的范围在
[0, 105]内 -1000 <= Node.val <= 1000
解题主线
- BFS 遇到第一个叶子即可返回。
- 递归时单侧子树为空不能直接取左右深度最小值。
解法 1:递归分类
单侧为空时只能走非空侧,两侧都存在时才取较小深度。
-
时间复杂度: O(n)
-
空间复杂度: O(h)
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
// 单侧为空时,最短根到叶路径只能经过非空子树
if (root.left == null) return minDepth(root.right) + 1;
if (root.right == null) return minDepth(root.left) + 1;
// 仅当左右子树都存在时,才能选择较小深度
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}解法 2:BFS 提前结束
逐层扩展,首个叶子的层号就是最小深度。
-
时间复杂度: O(n) 最坏
-
空间复杂度: O(w)
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()) {
depth++;
// 固定本层节点数,确保新增子节点留到下一层处理
for (int size = queue.size(); size > 0; size--) {
TreeNode node = queue.poll();
// BFS 按层扩展,遇到的第一个叶子必然具有最小深度
if (node.left == null && node.right == null) return depth;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return depth;
}
}边界与易错点
- 叶子必须同时没有左右孩子;空孩子本身不是叶子。
整理来源
由旧仓库源码复核、去重并整理;展示代码已按 Java 21 语义修正明显问题。
leetcode/src/main/java/tree/Q111_minDepth.java