Skip to main content

113. Path Sum II

https://leetcode.com/problems/path-sum-ii/

Python

class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
result = []

def dfs(node, path, current_sum):
if not node:
return

current_sum += node.val

if current_sum == targetSum and not node.left and not node.right:
result.append(path+[node.val])

dfs(node.left, path+[node.val], current_sum)
dfs(node.right, path+[node.val], current_sum)

dfs(root, [], 0)

return result