-
Notifications
You must be signed in to change notification settings - Fork 0
/
113 path sum 2.py
33 lines (32 loc) · 1.01 KB
/
113 path sum 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
# 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:
def __init__(self):
self.stack = []
self.ret = []
self.sum = 0
def setArgs(self, target):
self.target = target
def dfs(self, node): # node is not None
self.sum += node.val
self.stack.append(node.val)
if (not node.left) and (not node.right): #leaf
if self.sum == self.target:
self.ret.append(self.stack.copy())
else:
if(node.left):
self.dfs(node.left)
if node.right:
self.dfs(node.right)
self.sum -= node.val
self.stack.pop()
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
self.setArgs(targetSum)
if root is None:
return []
self.dfs(root)
return self.ret