Path Sum II
Solution Code
Definition for a binary tree node.class TreeNode:def init(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightclass Solution:def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:result = []def dfs(node, current_sum, path):
if not node:
return
path.append(node.val)
current_sum += node.val
# Check if it is a leaf node and the sum matches targetSum
if not node.left and not node.right:
if current_sum == targetSum:
result.append(list(path))
else:
dfs(node.left, current_sum, path)
dfs(node.right, current_sum, path)
# Backtrack
path.pop()
dfs(root, 0, [])
return resultTime Complexity
O(N^2)
Space Complexity
O(N)

