Path Sum III – Solution & Complexity
Solution Walkthrough
Step 1: Brute-force every possible starting node
- For each node, count how many downward paths starting exactly there sum to the remaining target.
- Then recurse into the left and right child as new starting points.
- This is easy to reason about and correct, but in a skewed tree it revisits many descendants for many different starts, so the worst-case time is
O(n^2).
Step 2: Use prefix sums plus a hash map for a single DFS
- Track the running sum from the root to the current node.
- A path ending at the current node sums to
targetSumwhenever an earlier prefix sum equalscurrentSum - targetSum. - Store counts of prefix sums in a hash map as you go down the tree, then decrement that count while backtracking so sibling paths do not accidentally reuse state from each other.
- This counts every valid downward path in
O(n)time withO(h)recursion stack plus up toO(n)prefix-sum storage.