-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path113.Path-Sum-II-v2.py
More file actions
31 lines (26 loc) · 946 Bytes
/
113.Path-Sum-II-v2.py
File metadata and controls
31 lines (26 loc) · 946 Bytes
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
# 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]]:
if not root:
return []
res = []
path = [root.val]
def dfs(root, curSum):
if not root.left and not root.right and curSum == targetSum:
res.append(path[:])
if root.left:
path.append(root.left.val)
dfs(root.left, curSum + root.left.val)
path.pop()
if root.right:
path.append(root.right.val)
dfs(root.right, curSum + root.right.val)
path.pop()
return
dfs(root, root.val)
return res