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