Path Sum solution explained
Path Sum asks whether any path from the root down to a leaf adds up to a target. Walk down the tree subtracting each node's value from the target, and when you reach a leaf, check whether what remains is zero. Each node is visited once, so it runs in O(n) time with O(h) memory for the recursion or stack.
By Evin JohnPublished 7 min read
The problem, reworded
You get the root of a binary tree of integers and a target number. A root-to-leaf path starts at the root and follows child pointers until it stops at a node with no children. Return true if the values along at least one such path add up exactly to the target. An empty tree has no paths, so the answer for it is false whatever the target is.
4
/ \
9 2
/ \ \
-3 6 5
/ \
8 -1| Target | Answer | Why |
|---|---|---|
| 19 | true | 4 + 9 + 6, and also 4 + 2 + 5 + 8 |
| 10 | true | 4 + 9 + (-3), and also 4 + 2 + 5 + (-1) |
| 6 | false | 4 + 2 is 6, but node 2 has a child, so the path has not ended |
| 13 | false | No root-to-leaf path adds to 13 |
The target 6 is the trap worth naming early. A path that hits the target at an inner node and keeps going does not count. Ask the interviewer to confirm the leaf rule, and ask whether values can be negative; here they can, which matters for the follow-ups below.
What the interviewer listens for
The code is short, so the signals are in the details: a correct definition of a leaf, a clean way to pass state down the tree, and no premature stopping. Many candidates also try to prune by stopping once the running sum passes the target. That only works when every value is positive, and the interviewer may give you negative numbers precisely to see whether you assume otherwise.
Brute force: list every path
You could build every root-to-leaf path as a list, add each one up and compare. It is correct, and it is a useful test reference, but it copies values into every path, which costs O(n·h) time and memory overall. There is no need to keep the paths when only a yes or no is wanted.
Subtract on the way down
Pass the target down, minus the current node's value. At a leaf, the path is complete, so the answer for that path is whether the remainder is exactly zero. At an inner node, the answer is true if either child's subtree has a path that finishes the job. The or short-circuits, so the search stops as soon as one path works.
def has_target_path(root, target):
if root is None:
return False
remaining = target - root.val
if root.left is None and root.right is None:
return remaining == 0 # only a leaf may end the path
return (has_target_path(root.left, remaining)
or has_target_path(root.right, remaining))Notice that a missing child returns false, which is right: an empty subtree contributes no path. That is also why the leaf test must happen at the node itself. If you only checked for zero when reaching a missing child, a node with one child would be treated as a path end on its empty side, and the target 6 in the example would wrongly return true.
function hasTargetPath(root, target) {
if (root === null) return false;
const stack = [[root, target - root.val]];
while (stack.length > 0) {
const [node, remaining] = stack.pop();
if (node.left === null && node.right === null && remaining === 0) return true;
if (node.right !== null) stack.push([node.right, remaining - node.right.val]);
if (node.left !== null) stack.push([node.left, remaining - node.left.val]);
}
return false;
}Trace for target 6
At the root the remainder becomes 6 - 4 = 2. The left branch through 9 leaves -7, then -4 at the leaf -3 and -13 at the leaf 6, neither zero. The right branch reaches node 2 with remainder 0, but node 2 is not a leaf, so the walk continues to 5 (remainder -5), then to the leaves 8 (-13) and -1 (-4). No leaf ends at zero, so the answer is false.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Build every path, then sum | O(n·h) | O(n·h) for the stored paths |
| Recursive subtraction | O(n) | O(h) call stack |
| Explicit stack of pairs | O(n) | O(h) for depth-first order |
| Breadth-first with a queue of pairs | O(n) | O(width of the widest level) |
Edge cases
- Empty tree: false, even for target 0.
- A single node: true exactly when its value equals the target.
- Negative values and a negative target: no special handling, as long as you do not prune.
- A target reached at an inner node: not an answer by itself.
- Very deep trees: recursion depth equals the height, so a long chain may need the stack version in Python.
Mistakes to avoid
- Treating a node with one child as a leaf.
- Checking for a zero remainder at a missing child instead of at a real leaf.
- Stopping early when the running sum exceeds the target, which is wrong with negative values.
- Returning true for an empty tree with target 0.
- Keeping a shared running total and forgetting to subtract the node again on the way back up. Passing the remainder as an argument avoids this entirely.
Follow-up questions
- Return every path that matches. That is Path Sum II, which adds a path list and backtracking.
- Count paths that start and end anywhere, as long as they go downward. Carry a map of prefix sums from the root to the current node; at each node, look up how many earlier prefixes differ from the current one by the target. That is O(n).
- The largest sum on any path, not a fixed target. A post-order walk that returns each subtree's best downward gain.
- Every value is positive. Then pruning is safe: stop exploring once the remainder goes below zero.
How to explain it
Fictional example
- Candidate
- I'll pass the remaining target down the tree, subtracting each node's value. That way each call only needs its own number.
- Candidate
- The check happens at leaves only: no left and no right child. If the remainder there is zero, I've found a path. Hitting zero at an inner node doesn't count, since the path has to end at a leaf.
- Candidate
- Values can be negative, so I won't prune. Each node is visited once, linear time, with stack depth equal to the tree's height.
Related walkthroughs
Path Sum II returns the matching paths themselves. Symmetric Tree is another short recursion where getting the base case right is most of the work. Count Good Nodes in Binary Tree also carries a value from parent to child, in that case the largest value seen so far. The coding problems hub lists the rest.
How Natively can help you prepare
If you practice on Mac or Windows, Natively can take a screenshot of this problem and help you build a test tree where the target is reached at an inner node, the case that catches most bugs. It saves a transcript and notes of your practice interview, which makes it easy to review how you stated the leaf rule. The AI interview assistant page explains how it works.
Questions people ask
How do you solve Path Sum?
Recurse down the tree passing the target minus each node's value. At a leaf, return whether the remainder is zero; at an inner node, return true if either child's subtree has a matching path. An empty tree returns false.
Does a path in Path Sum have to end at a leaf?
Yes. Reaching the target at a node that still has children does not count, which is the most common bug in this problem.
Can you stop early in Path Sum when the sum gets too big?
Only if every value is positive. With negative values a sum can overshoot and come back, so pruning would miss valid paths.
What is the time complexity of Path Sum?
O(n) time, since each node is visited at most once, and O(h) space for the recursion or stack, where h is the tree's height.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
