Skip to the solution
EasyDSA13 min read

How do you check if a root-to-leaf path sums to a target?

609 views

The problem

Question presented to candidate: "Given the root of a binary tree and an integer target, write a Python function that returns True if some path from the root down to a leaf has values adding up to exactly the target. Then tell me how you would return all such paths."

What a strong answer should cover:

  • Carry the remaining target down: subtract the node's value, and at a leaf check that the remainder is 0.
  • A leaf has no children; a one-child node is not a leaf, so [1, 2] with target 1 is False.
  • O(n) time, O(h) space; the short-circuit or stops at the first valid path; negative values mean no pruning.
  • Follow-up: all paths with backtracking (append, recurse, pop) and a copy at each match.
  • Python specifics: ints never overflow; store list(path) (a copy) or every stored path is the same list that later gets emptied; the recursion limit of 1000 suggests an iterative (node, remaining) stack for deep trees.

Clarifying questions expected:

  • "Must the path end at a leaf, and start at the root?"
  • "Can the values or the target be negative?"

Code / implementation expected: Yes โ€” a short recursive Python function; optionally the iterative stack and the all-paths version.

  • trees
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive hasPathSum on ten cases, including the one-child trap and negatives
PythonIterative stack, the null-base-case bug, all matching paths, and 64-bit sums

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 24 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you invert a binary tree?

Continue