https://leetcode.cn/problems/path-sum-ii/
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
# DFS 回溯 前序遍历
# from copy import deepcopy
# path, result = [], []
# def dfs(node, target):
# if not node:
# return
# path.append(node.val)
# target -= node.val
# if not node.left and not node.right and target == 0:
# result.append(deepcopy(path))
# # result.append(path[:])
# dfs(node.left, target)
# dfs(node.right, target)
# path.pop()
# dfs(root, targetSum)
# return result
# BFS
from collections import deque
if not root:
return []
q = deque([[root, [], 0]])
result = []
while q:
node, path, cursum = q.popleft()
if not node.left and not node.right and cursum + node.val == targetSum:
result.append(path + [node.val])
if node.left:
q.append((node.left, path + [node.val], cursum + node.val))
if node.right:
q.append((node.right, path + [node.val], cursum + node.val))
return result