Does a root-to-leaf route add up to a target?

Trees Junior Python 3.13+ Reviewed By Best Latest Apps

Pick the fix

Root 1 has only a left child 2. Target is 1. What should the function return?

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A False, because the only leaf route is 1 + 2 = 3

Right: the root is not a leaf when it has a child.

The question counts only routes that end where both children are missing.

Why not the others?
  • B True, because the root alone is 1. A route must end at a leaf; the root has a child, so it is not one.
  • C True, because an empty right side adds 0. Missing children are not leaves.

30-second answer

Subtract each node's value from the target on the way down. At a leaf, the route works if what is left is zero. Return True as soon as any branch succeeds. O(n) time, O(h) stack.

Practise saying it · 30 s. No recording, just a timer

Explain the root-to-leaf target check.

Say your answer out loud, then check which of these points you covered:

  • Subtract on the way down
  • Check at leaves only
  • O(n)

Deep dive

The 'leaf' condition matters: a node with one child is not the end of a route.

Passing the remaining target down is cleaner than building route totals on the way up.

To list all routes, carry the route as a list and copy it at each leaf (backtracking).

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def route_hits(root: Node | None, target: int) -> bool:
    if root is None:
        return False
    left = target - root.val
    if not (root.left or root.right):
        return left == 0  # a leaf: the route ends here
    return route_hits(root.left, left) or route_hits(root.right, left)

Common mistakes

  • Stopping at a node with one missing child, treating it as a leaf.
  • Returning True for an empty tree with target 0; usually the answer is False.

Senior take & follow-ups

Mention the leaf condition before you code; it is the edge case interviewers watch for.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you count routes that start and end anywhere going down?

    Show hint

    Prefix sums along the current route with a hash map, O(n).

  2. What about negative values?

    Show hint

    This solution still works; you cannot prune early when the total passes the target.

What each operation costs: Binary Tree · Binary Search Tree · Tree Traversal

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.