-
Notifications
You must be signed in to change notification settings - Fork 481
/
0113.py
49 lines (40 loc) · 1.4 KB
/
0113.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
49
# class Solution:
# def pathSum(self, root, sum):
# """
# :type root: TreeNode
# :type sum: int
# :rtype: List[List[int]]
# """
# result = list()
# if not root:
# return result
# stack = [(list(), sum, root)]
# while stack:
# path, val_, node = stack.pop()
# if node:
# path.append(node.val)
# if not node.left and not node.right and val_ == node.val:
# result.append(path)
# stack += [(path.copy(), val_ - node.val, node.left), (path.copy(), val_ - node.val, node.right)]
# return result
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
result = list()
if not root:
return result
self._pathSum(result, list(), root, sum)
return result
def _pathSum(self,result, path, node, num):
if node:
path.append(node.val)
if not node.left and not node.right and num == node.val:
result.append(path.copy())
return
self._pathSum(result, path, node.left, num - node.val)
self._pathSum(result, path, node.right, num - node.val)
path.pop()