Problem 616
Path Sum III
Medium · 20 pts · Tree, Depth-First Search, Prefix Sum
Problem
Count the paths in a binary tree whose values add up to a target T. A path must go downwards (from a node to one of its descendants, or a single node), but it does not have to start at the root or end at a leaf. Paths with the same values at different places count separately. During a depth-first search, keep a map of the prefix sums on the current root-to-node path; the number of paths ending at a node equals the count of earlier prefixes equal to (current sum - T).
Input
The first line contains T. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children.
Output
Print the number of downward paths with sum T.
Constraints
1 <= number of nodes <= 1000; -10^9 <= value <= 10^9; -1000 <= T <= 1000
Example input
8 11 10 5 -3 3 2 null 11 3 -2 null 1
Example output
3
Explanation
With T = 8 in the tree 10 5 -3 3 2 null 11 3 -2 null 1, the paths 5 → 3, 5 → 2 → 1 and -3 → 11 each add up to 8. So the answer is 3.