A binary tree starts at root, and you also get a whole number targetSum. A root-to-leaf path starts at the root and walks down, one child at a time, until it reaches a leaf: a node with no children at all.
Return true if some root-to-leaf path has values that add up to exactly targetSum, and false otherwise. An empty tree has no paths.
Example 1
Input: root = [3, 9, -2, 1, null, 6, 4], targetSum = 7 Output: true Why: 3 + (−2) + 6 = 7, and 6 is a leaf
2 more examples and the constraints
Example 2
Input: root = [2, 5, 6], targetSum = 2 Output: false Why: the root is 2 but not a leaf; the paths add to 7 and 8
Example 3
Input: root = [], targetSum = 0 Output: false Why: an empty tree has no path at all
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 with running sumsO(n)
- Recursive DFS, subtract as you goO(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 tree of 5,000 nodes | Verdict |
|---|---|---|---|
| BFS with running sums | O(n) | Passes; holds a whole level | |
| Recursive DFS, subtract as you go | O(n) | Best; shortest code |
n = number of nodes, w = widest level, h = height. Both stop at the first matching leaf.
Edge cases to test
- Empty tree. There is no path, so even a target of 0 gives false.
- The target is reached at an inner node. [2, 5, 6] with target 2: the root is not a leaf, so it does not count.
- One child only. [1, null, 2] has one leaf, 2. The empty left slot is not a leaf and must not count as a path.
- Negative values. A sum can go past the target and come back, so you cannot stop early when the running sum gets too big.
Common mistakes
- Returning true when the remaining target hits 0 at a node that still has children.
- Treating an empty child as a leaf, so [1, null, 2] with target 1 wrongly passes.
- Pruning when the running sum exceeds the target, which breaks with negative values.
How to talk through it
- 1Clarify. Must the path end at a leaf? Can values be negative? What should an empty tree return?
- 2Shrink the problem. A path from the root works if a path from a child adds up to the target minus the root.
- 3Name the base cases. An empty node is false; a leaf is true when the rest is 0.
- 4Give the cost. O(n) time; O(h) stack, which is O(n) for a chain. Mention BFS with sums if recursion depth is a worry.
- 5Test out loud. Run the empty tree, a root that equals the target but has children, and a one-child node.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?