SDE & MLE Prep

113. Path Sum II

Problem

Return every root-to-leaf path (as a list of node values) whose values add up to targetSum.

Example: [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 → [[5,4,11,2],[5,8,4,5]]

DFS with a path list; at a leaf with the right remainder, copy the path. Pop on the way back (backtracking).

Complexity: O(n²) worst case (copying paths).

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

        def dfs(node, rest):
            if not node:
                return
            path.append(node.val)
            rest -= node.val
            if not node.left and not node.right and rest == 0:
                res.append(path[:])
            dfs(node.left, rest)
            dfs(node.right, rest)
            path.pop()

        dfs(root, targetSum)
        return res