path sum ii

又一道divde and conquer的题目

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
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class (object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
ret = []
self.helper(root, [], sum, ret)
return ret
def helper(self, root, cur, sum, ret):
if not root:
return
if not root.left and not root.right and sum - root.val == 0:
cur.append(root.val)
ret.append(cur[:])
cur.pop()
return
for node in [root.left, root.right]:
sum -= root.val
cur.append(root.val)
self.helper(node, cur, sum, ret)
sum += root.val
cur.pop()