You get the root of a binary tree and a whole number targetSum. A root-to-leaf path begins at the root and steps down one child at a time until it stops at a leaf, a node that has no children.
Return every root-to-leaf path whose values add up to exactly targetSum. Give each path as the list of its values from top to bottom. The paths can be listed in any order, and an empty tree has none.
Example 1
Input: root = [6, 1, 3, 2, 0, 0], targetSum = 9 Output: [[6, 1, 2], [6, 3, 0]] Why: 6 + 1 + 2 = 9 and 6 + 3 + 0 = 9; 6 + 1 + 0 is only 7
2 more examples and the constraints
Example 2
Input: root = [2, 5, 6], targetSum = 2 Output: [] Why: the root is 2 but has children; the paths add to 7 and 8
Example 3
Input: root = [], targetSum = 0 Output: [] Why: an empty tree has no paths
Constraints
- The tree has between 0 and 5,000 nodes
- −1,000 ≤ each node value ≤ 1,000
- −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.
- BFS, each node carries its pathO(n·h)
- Backtracking DFS, one shared pathO(n + k·h)
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 5,000 nodes | Verdict |
|---|---|---|---|
| BFS, each node carries its path | O(n·h) | Passes; copies a path per node | |
| Backtracking DFS, one shared path | O(n + k·h) | Best; copies only answers |
n = number of nodes, h = height, k = number of matching paths.
Edge cases to test
- Empty tree. There are no paths, so the answer is [] even for a target of 0.
- The target is reached at an inner node. [2, 5, 6] with target 2: the root is not a leaf, so [2] is not a path.
- One child only. [1, null, 2] with target 1: the empty left slot is not a leaf, so the answer is [].
- Negative values. A running sum can pass the target and come back, so never cut a branch because the sum got too big.
- Equal paths. [1, 2, 2] with target 3 has two different paths with the same values. Both are listed.
Common mistakes
- Storing
pathitself instead of a copy, so every stored answer ends up empty. - Forgetting to pop on the way out, so values from one branch leak into the next.
- Accepting a node with no children check, or treating an empty child as a leaf.
How to talk through it
- 1Clarify. Must a path end at a leaf? Can values be negative? Is the order of the paths important?
- 2Start from Path Sum. Same DFS that subtracts as it goes down; now it also has to remember the values on the way.
- 3Share one list. Append on the way in, pop on the way out, and copy only at a leaf that matches.
- 4Give the cost. O(n) visits plus the cost of copying answers; O(h) extra space for the stack and the path.
- 5Test out loud. Run an empty tree, a root that equals the target but has children, and a node with one child.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?