树与图简单2 种解法
#111二叉树的最小深度
计算根节点到最近叶子节点的节点数。
#二叉树#深度优先搜索#广度优先搜索
解题主线
01
BFS 遇到第一个叶子即可返回。
02
递归时单侧子树为空不能直接取左右深度最小值。
解法 1:递归分类
单侧为空时只能走非空侧,两侧都存在时才取较小深度。
时间复杂度
O(n)
空间复杂度
O(h)
java
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)
java
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();
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