Path Sum II

35 min · pathSum()

A delivery route only counts when it reaches a destination. A promising subtotal halfway down the map isn't enough.

You're given the root of a binary tree and an integer targetSum. A root-to-leaf path starts at the root, follows child links, and stops at a node with no children. Return every such path whose node values add up to targetSum. Put the root value first and the leaf value last in each returned array.

A few ground rules:

  • The outer list may contain the matching paths in any order.
  • The values inside each path must stay in root-to-leaf order.
  • A sum reached at a node that still has a child doesn't count.
  • Return [] when the tree is empty or no complete path matches.

Constraints

  • 0 <= node count <= 5_000
  • -1_000 <= node.val <= 1_000
  • -100_000_000 <= targetSum <= 100_000_000

Hints

Carry the subtotal

As you move from a parent to a child, add the child's value to one running sum. You don't need to add the whole path again at every node.

A match needs a leaf

Check the target only when both child links are empty. That condition prevents a matching prefix from sneaking into the answer.

Undo before the sibling

Use depth-first search (DFS), which follows one branch before returning to try another. Append when you enter a node, copy the list when a leaf matches, then remove the node before exploring a different branch.

Follow-up

Can you keep only one working path instead of copying every partial path along the way?

Visible cases

Examples

Example 1

ready
Input
root = [
  5,
  4,
  8,
  11,
  null,
  13,
  4,
  7,
  2,
  null,
  null,
  5,
  1
]
targetSum = 22
Expected
[
  [
    5,
    4,
    11,
    2
  ],
  [
    5,
    8,
    4,
    5
  ]
]
Why
two different leaves complete a sum of 22

Example 2

ready
Input
root = [
  1,
  2,
  3
]
targetSum = 5
Expected
[]
Why
neither complete root-to-leaf path sums to 5

Example 3

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

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite