Path Sum

25 min · hasPathSum()

A route can hit the right total halfway down a tree and still be the wrong route. The finish line matters.

Given a binary tree's root and an integer targetSum, return true when at least one root-to-leaf path — a downward route that starts at the root and ends at a node with no children — has values adding to exactly targetSum.

Keep the endpoint rule sharp:

  • A leaf has neither a left child nor a right child.
  • Stopping at an internal node doesn't count, even if the running sum matches.
  • Values and the target may be negative, zero, or positive.
  • An empty tree has no root-to-leaf path, so it always returns false.

Constraints

  • 0 <= number of nodes <= 10_000
  • -1_000 <= node.val <= 1_000
  • -100_000_000 <= targetSum <= 100_000_000

Hints

Write down every finish

The direct approach collects the sum of each complete root-to-leaf route, then asks whether targetSum appears in that collection.

Carry what remains

Instead of rebuilding a path at every leaf, subtract each visited value from the target. What must the remainder be when you reach a leaf?

Check the leaf, not just the number

A remainder of zero is an answer only when the current node has no children. Otherwise the route hasn't finished.

Follow-up

How would you return one matching root-to-leaf path instead of only true or false?

Visible cases

Examples

Example 1

ready
Input
root = [
  5,
  4,
  8,
  11,
  null,
  13,
  4,
  7,
  2,
  null,
  null,
  null,
  1
]
targetSum = 22
Expected
true
Why
the route 5 → 4 → 11 → 2 ends at a leaf and totals 22

Example 2

ready
Input
root = [
  1,
  2,
  3
]
targetSum = 5
Expected
false
Why
the complete route totals are 3 and 4, not 5

Example 3

ready
Input
root = []
targetSum = 0
Expected
false
Why
an empty tree has no root-to-leaf route

Interview signal

Asked at

AmazonMetaBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite