
BFS比DFS合适,因为BFS遇到第一个叶子结点就可直接返回结果,而DFS要遍历整棵树
我再写一遍递归和BFS:
1、递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(root.right)
childDepth = min(selfDepth, rightDepth) if leftDepth and rightDepth else leftDepth or rightDepth
return childDepth + 1
2、BFS
if not root: return 0
queue = [root]
depth = 0
while queue:
for _ in range(len(queue)):
cur = queue.pop(0)
if not cur.left and not cur.right:
return depth + 1
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
depth += 1

本文深入探讨了宽度优先搜索(BFS)与深度优先搜索(DFS)在树形数据结构搜索中的表现差异,指出BFS在寻找最短路径时的优越性,并通过递归与BFS两种实现方式的代码示例,清晰地展示了两种算法的工作原理。
2112

被折叠的 条评论
为什么被折叠?



