90/300
- 路径总和 II
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树;[5,4,8,11,null,13,4,7,2,null,null,5,1],以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
思路: stack
sum(整个叶子的路径),看是否为所需。
画了丑图,配合代码食用:
# Definition for a binary tree node.
# 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]]: #注意原题给的sum,覆盖了函数名,所以改成s
if not root: return []
stack = [(root,[root.val])]
res = []
while stack:
node, lst = stack.pop()
if not node.left and not node.right and sum(lst) ==s:
res.append(lst)
continue
if node.right:
stack.append((node.right, lst + [node.right.val]))
if node.left:
stack.append((node.left, lst + [node.left.val]))
return res
recursion:
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res = []
def helper(node, sum, path):
if not node: return
path.append(node.val)
if not node.left and not node.right and node.val == sum:
res.append(path[:])
path.pop()
return
helper(node.left, sum-node.val, path)
helper(node.right, sum-node.val, path)
path.pop()
helper(root, sum, [])
return res
so-far 二叉树类型题:
104 二叉树的最大深度
112 路径总和
113 路径总和 II