InterviewPrepKit

Home / Coding / Trees

Path Sum III

medium Original β†—
Solving tips
  • Recognize this as the tree version of 'count subarrays summing to k' (LeetCode 560): a root-to-node path is a prefix sum.
  • DFS carrying the running root-to-here sum and a hash map count[prefix]; at each node add count[running - targetSum] to the answer for O(n) time, O(n) space.
  • Seed count[0] = 1 so paths starting at the root are counted.
  • Pitfall: decrement count[running] when backtracking, or prefixes from one subtree leak into the sibling and overcount; don't early-return on hitting the target since negatives let a longer path hit it again.

Problem

Given the root of a binary tree and an integer targetSum, count how many downward paths in the tree have values summing to targetSum. A path may start at any node and end at any node below it, but it must go strictly downward (each step parent β†’ child) and contain at least one node. Values may be negative, and the answer counts paths, not nodes.

Examples

  • Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 β†’ Output: 3 The qualifying paths are 5 β†’ 3, 5 β†’ 2 β†’ 1, and -3 β†’ 11.
  • Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 β†’ Output: 3 Paths: 5 β†’ 4 β†’ 11 β†’ 2, 4 β†’ 11 β†’ 7, and 5 β†’ 8 β†’ 4 β†’ 5.
  • Input: root = [1,-1,null,1], targetSum = 0 β†’ Output: 2 In this left-leaning chain 1 β†’ -1 β†’ 1, the paths 1 β†’ -1 and -1 β†’ 1 each sum to 0; the full chain sums to 1 and single nodes don’t qualify.

Constraints

  • Up to 1000 nodes; -10^9 <= Node.val <= 10^9; -1000 <= targetSum <= 1000.
  • Negative values mean a running sum can revisit earlier totals β€” no pruning by β€œsum already too big”.
  • O(nΒ²) passes at this size, but the intended solution is O(n).

Think about it first

Hint 1 Every downward path is described by two nodes: where it starts and where it ends. What if you fix the starting node and search downward from it?
Hint 2 In arrays, "count subarrays summing to k" is solved with prefix sums and a hash map: a subarray sums to k exactly when two prefixes differ by k. A root-to-node path is a prefix here.
Hint 3 DFS while carrying the running root-to-current sum and a hash map counting how often each prefix sum occurred on the current root path. At each node, add `count[current - targetSum]` to the answer β€” and decrement the node's own entry when backtracking so counts never leak across branches.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.