-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path113.Path-Sum-II.py
More file actions
34 lines (31 loc) · 1.07 KB
/
113.Path-Sum-II.py
File metadata and controls
34 lines (31 loc) · 1.07 KB
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
# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
path = []
res = []
if not root:
return res
def backtracking(node, cur_sum):
nonlocal path, res
if not node.left and not node.right:
if cur_sum != targetSum:
return
else:
res.append(path[:])
return
if node.left:
path.append(node.left.val)
backtracking(node.left, cur_sum + node.left.val)
path.pop()
if node.right:
path.append(node.right.val)
backtracking(node.right, cur_sum + node.right.val)
path.pop()
path.append(root.val)
backtracking(root, root.val)
return res