-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path113.路径总和2.py
48 lines (41 loc) · 1.2 KB
/
113.路径总和2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
#
# 说明: 叶子节点是指没有子节点的节点。
#
# 示例:
# 给定如下二叉树,以及目标和 sum = 22,
#
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1
# 返回:
#
# [
# [5,4,11,2],
# [5,8,4,5]
# ]
# 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, sum: int) -> List[List[int]]:
res = []
if not root: return []
def helper(root, sum_, tmp):
if not root:
return
if not root.left and not root.right and sum_ - root.val == 0:
tmp += [root.val]
res.append(tmp)
return
helper(root.left, sum_ - root.val, tmp + [root.val])
helper(root.right, sum_ - root.val, tmp + [root.val])
helper(root, sum, [])
return res