返回
LeetCode 111:二叉树的最小深度
闲谈
2023-10-21 16:20:18
【问题】
给定一个二叉树,找出其最小深度。
二叉树的最小深度是指从根节点到最近叶节点的最短路径上的节点数。
例如,给定以下二叉树:
1
/ \
2 3
/ \ \
4 5 6
最小深度是 2,路径为 1 -> 2 -> 4。
【解决方案】
1. 深度优先遍历
深度优先遍历(DFS)是一种以深度优先的方式遍历二叉树的算法。在 DFS 中,我们将从根节点开始,并递归地访问其左子树和右子树。当我们到达叶节点时,我们将记录下当前的深度。
为了实现 DFS,我们可以使用以下 Python 代码:
def min_depth_dfs(root):
if root is None:
return 0
# 如果当前节点是叶节点,则返回深度 1
if root.left is None and root.right is None:
return 1
# 如果当前节点只有左子树,则递归访问左子树
if root.left is not None and root.right is None:
return min_depth_dfs(root.left) + 1
# 如果当前节点只有右子树,则递归访问右子树
if root.left is None and root.right is not None:
return min_depth_dfs(root.right) + 1
# 如果当前节点既有左子树又有右子树,则递归访问左右子树并取最小深度
return min(min_depth_dfs(root.left), min_depth_dfs(root.right)) + 1
2. 广度优先遍历
广度优先遍历(BFS)是一种以广度优先的方式遍历二叉树的算法。在 BFS 中,我们将从根节点开始,并逐层访问其所有子节点。当我们访问到一层的所有节点后,我们将继续访问下一层的所有节点。
为了实现 BFS,我们可以使用以下 Python 代码:
def min_depth_bfs(root):
if root is None:
return 0
# 创建一个队列,并将根节点加入队列
queue = [root]
# 设置最小深度为无穷大
min_depth = float('inf')
# 循环遍历队列
while queue:
# 将当前层的节点数存储在变量 size 中
size = len(queue)
# 循环遍历当前层的每个节点
for _ in range(size):
# 从队列中取出当前节点
node = queue.pop(0)
# 如果当前节点是叶节点,则更新最小深度
if node.left is None and node.right is None:
min_depth = min(min_depth, depth)
# 将当前节点的左子树和右子树加入队列
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
# 增加深度
depth += 1
# 返回最小深度
return min_depth
3. 优化技巧
为了提高求解此问题的效率,我们可以采用以下优化技巧:
- 剪枝 :在 DFS 或 BFS 过程中,如果我们发现当前节点的深度已经大于当前的最小深度,则我们可以停止对该节点的子节点进行访问。
- 记忆化 :我们可以使用记忆化来存储已经计算过的子树的最小深度。这样,当我们再次访问相同的子树时,我们可以直接从记忆化中获取结果,而无需重新计算。
【结语】
在本文中,我们介绍了两种求解 LeetCode 111:二叉树的最小深度的