-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path113 Path Sum II.py
57 lines (51 loc) · 1.46 KB
/
113 Path Sum II.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
50
51
52
53
54
55
56
57
"""
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
Author: Rajeev Ranjan
"""
# 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, sum):
"""
:param root: TreeNode
:param sum: integer
:return: a list of lists of integers
"""
result = []
self.accumulatePathSum(root, sum, [], result)
return result
def accumulatePathSum(self, root, sum, cur_path, result):
"""
DFS
Similar to previous path sum
"""
# trivial
if not root:
return
sum = sum - root.val
cur_path.append(root.val)
# terminal condition
if sum==0 and root.left is None and root.right is None:
result.append(list(cur_path)) # new copy
return
# dfs with pre-checking
if root.left: self.accumulatePathSum(root.left, sum, list(cur_path), result) # new copy
if root.right: self.accumulatePathSum(root.right, sum, list(cur_path), result) # new copy