1. 二叉树最小深度
方法一:递归实现
class Solution:
def minDepth(self, root: TreeNode) -> int:
# sanit checks
if not root:
return 0
children=[root.left,root.right]
# 左右都为叶子节点,返回1
if children==[None,None]:
return 1
count=float('inf')
for child in children:
if child: # 不为空,才计数
count=min(self.minDepth(child),count)
return count+1
方法二:BFS算法实现
from collections import deque
class Solution:
def minDepth(self, root: TreeNode) -> int:
# BFS解法
# sanit checks
if not root:
return 0
# 初始化栈,使用双向队列来的实现
# 初始栈包含一个root节点,初始depth为1
stack = deque([root])
depth = 1
# 当stack不为空时,进行如下循环
while stack:
sz = len(stack)
for _ in range(sz):
# 将节点从栈顶逐个弹出
cur = stack.popleft()
# 如果本节点为叶子节点,则返回depth
if not cur.left and not cur.right:
return depth
# 如果本节点包含左子节点,则将左子节点压入栈
if cur.left:
stack.append(cur.left)
# 如果本节点包含右子节点,则将右子节点压入栈
if cur.right:
stack.append(cur.right)
# 将depth自增1
depth+=1
return depth