-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path113. Path Sum II.py
38 lines (30 loc) · 956 Bytes
/
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
s = 0
res = []
path = []
targetSum = 0
def dfs(self, node: Optional[TreeNode]) -> None:
if not node.left and not node.right:
if self.s + node.val == self.targetSum:
self.res.append(self.path + [node.val])
return
self.path.append(node.val)
self.s += node.val
if node.left: self.dfs(node.left)
if node.right: self.dfs(node.right)
self.path.pop()
self.s -= node.val
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root: return []
self.s = 0
self.res = []
self.path = []
self.targetSum = targetSum
self.dfs(root)
return self.res