A binary tree is handed to you by its root, together with a number targetSum. Count the paths whose node values add up to exactly targetSum.
A path is a chain of one or more nodes that only moves downward, from a parent to one of its children. It can begin at any node and stop at any node below it; it does not have to touch the root or a leaf.
Example 1
Input: root = [3, 1, -2, 2, null, 2], targetSum = 3 Output: 3 Why: [3], [1, 2] and [3, -2, 2] each add up to 3
2 more examples and the constraints
Example 2
Input: root = [4, 2, 6, 1, 3, null, -2], targetSum = 6 Output: 2 Why: [4, 2] and [6] add up to 6
Example 3
Input: root = [0, 0, 0], targetSum = 0 Output: 5 Why: three single nodes and two parent-child pairs
Constraints
- The tree has between 0 and 1,000 nodes
- −10⁹ ≤ each node value ≤ 10⁹
- −1,000 ≤ targetSum ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Start a search at every nodeO(n²)
- Prefix sums on the way downO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a chain of 1,000 nodes | Verdict |
|---|---|---|---|
| Start a search at every node | O(n²) | Passes, but quadratic on a chain | |
| Prefix sums on the way down | O(n) | Best; one visit per node |
n = number of nodes, h = height of the tree.
Edge cases to test
- An empty tree. [] has no paths at all: return 0.
- Zeros and a zero target. In [0, 0, 0] every node and every parent-child pair counts, 5 in all; the map keeps counts, not just a yes or no.
- Negative values. A path can reach the target, go past it, and come back. Never stop a search early because the sum is too big.
- Sums past 32 bits. A branch of 10⁹ values passes 2³¹ after three nodes; the sums need 64-bit integers.
Common mistakes
- Forgetting to lower the count when leaving a node, so a prefix from the left branch matches a node on the right.
- Starting the map empty instead of
{0: 1}, which misses every path that begins at the root. - Stopping a downward search at the first match, which misses longer paths that come back to the target through negative values.
How to talk through it
- 1Clarify. Must a path go downward only? Can it start and end anywhere? Can values be negative?
- 2Give the brute force. From every node, walk down and count where the sum hits the target: O(n²) on a chain.
- 3Spot the prefix sums. Along one branch this is Subarray Sum Equals K: a path ending here sums to target when an earlier prefix equals total − target.
- 4Handle the branches. Keep only the current branch in the map: add on the way down and remove on the way back. O(n) time and space.
- 5Test out loud. Run an empty tree, all zeros with target 0, and a path that starts below the root.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?