SDE & MLE Prep

437. Path Sum III

Problem

Count the paths whose node values add up to targetSum. A path may start and end at any nodes but must go downwards (parent to child only).

Example: [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 → 3

Constraints: up to 1000 nodes; sums can exceed 32 bits.

Paths go downward but can start anywhere → prefix sums on the root-to-node path (like 560). Count earlier prefixes equal to cur − target; undo the count when backtracking.

Complexity: O(n).

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
        seen = defaultdict(int, {0: 1})

        def dfs(node, cur):
            if not node:
                return 0
            cur += node.val
            cnt = seen[cur - targetSum]
            seen[cur] += 1
            cnt += dfs(node.left, cur) + dfs(node.right, cur)
            seen[cur] -= 1                     # backtrack
            return cnt

        return dfs(root, 0)