113.路径总和 II
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
叶子节点:没有子节点的节点。
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1 sum=22
[
[5,4,11,2],
[5,8,4,5]
] 返回
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, s: int) -> List[List[int]]:
if not root:
return []
res = []
stack = [(root, [root.val])] # (当前节点,路径数组[])
while stack:
cur, ls = stack.pop()
if not cur.left and not cur.right and sum(ls) == s:
res.append(ls)
if cur.right:
stack.append((cur.right, ls + [cur.right.val]))
if cur.left:
stack.append((cur.left, ls + [cur.left.val]))
return res
# DFS + stack