Path Sum II solution explained

Path Sum II returns every root-to-leaf path whose values add up to a target. Walk the tree depth first with one shared list holding the current path: append a node on the way down, and at a leaf with a zero remainder, save a copy of the list. Then remove the node on the way back up. The walk is O(n), and copying the matches adds up to O(n·h) in the worst case.

By Published 7 min read

The problem, reworded

You are given a binary tree of integers and a target. Find every path that starts at the root, follows child links down, and ends at a leaf, a node without children, such that the values on it add up to the target. Return them as a list of lists, each listing the values from root to leaf. If none match, return an empty list.

             3
           /   \
          1     5
         / \   / \
        4   6 -2   2
       /          / \
      1          1   0
A tree drawn for this page. Leaf paths sum to 9, 10, 6, 11 and 10.
Targets run against the tree above, output from the code below
TargetPaths returned
10[[3, 1, 6], [3, 5, 2, 0]]
9[[3, 1, 4, 1]]
6[[3, 5, -2]]
8[], since 3 + 5 reaches 8 only at an inner node
Targets run against the tree above, output from the code below. Scroll sideways on a small screen.

Clarify whether the order of the returned paths matters. The code below lists them left to right, the order a depth-first walk visits leaves, and most graders accept any order. Also confirm that values may be negative, which rules out stopping early when a running sum overshoots.

Why it follows Path Sum

This is usually asked right after the yes-or-no Path Sum, and the new skill it tests is backtracking with shared state. A candidate who builds a fresh list at every node gets a correct but wasteful answer. A candidate who shares one list but forgets to copy it when saving a match gets a list of empty or identical paths, a bug that is confusing to debug live. Interviewers watch for both.

Straightforward version: new list at every node

Pass a new list down each branch, path + [node.val], and save it when a leaf matches. It is easy to reason about, since no call can disturb another's list. The cost is a full copy at every node, so a deep tree pays O(h) per node even on branches that never match, for O(n·h) total work even when nothing is found.

One shared list with backtracking

Keep a single list for the current path. When entering a node, append its value and subtract it from the remainder. If the node is a leaf and the remainder is zero, save a copy of the list. Otherwise recurse into both children. Before returning, pop the node's value so the list matches the parent's path again. Only matches are copied, which is the work you cannot avoid because they are the output.

def target_paths(root, target):
    found, path = [], []
    def walk(node, remaining):
        if node is None:
            return
        path.append(node.val)
        remaining -= node.val
        if node.left is None and node.right is None:
            if remaining == 0:
                found.append(list(path))  # copy: path keeps changing
        else:
            walk(node.left, remaining)
            walk(node.right, remaining)
        path.pop()  # undo before returning to the parent
    walk(root, target)
    return found
Python: append, recurse, pop. Copies only on a match.
function targetPaths(root, target) {
  const found = [];
  const path = [];
  function walk(node, remaining) {
    if (node === null) return;
    path.push(node.val);
    remaining -= node.val;
    if (node.left === null && node.right === null) {
      if (remaining === 0) found.push([...path]);
    } else {
      walk(node.left, remaining);
      walk(node.right, remaining);
    }
    path.pop();
  }
  walk(root, target);
  return found;
}
JavaScript: the same backtracking; the spread makes the copy.

Trace for target 10

The path grows to [3, 1, 4, 1]; that leaf leaves a remainder of 1, so nothing is saved, and the two pops return to [3, 1]. Next comes [3, 1, 6], a leaf with remainder 0, so a copy is saved. Pops return to [3]. On the right, [3, 5, -2] leaves 4, [3, 5, 2, 1] leaves -1, and [3, 5, 2, 0] leaves 0, so the second copy is saved. Every append has a matching pop, so the list is empty again when the walk ends.

The copy is the line people get wrong. If you saved path itself instead of a copy, every saved entry would be the same list object, and after the final pops each one would be empty.

Complexity

n nodes, height h, L leaves
VersionTimeExtra space beyond the output
New list at every nodeO(n·h)O(h²) for the lists alive along one branch
Shared list with backtrackingO(n) for the walk plus O(h) per saved matchO(h) for the path and the call stack
n nodes, height h, L leaves. Scroll sideways on a small screen.

The output itself can be large: up to L paths, each up to h values long. For a long chain that ends in a fan of matching leaves, copying alone is O(n·h), which is O(n²). No algorithm can beat the size of what it must return, which is why the worst case is quoted in terms of copying.

Edge cases

  • Empty tree: an empty list.
  • Single node equal to the target: one path holding that value.
  • Several matching paths that share a prefix: each saved copy must be independent, which the copy guarantees.
  • Negative values: a partial sum may pass the target and come back, so do not prune.
  • Zero-valued leaves under a matching node: the path still has to end at the leaf, as with [3, 5, 2, 0] above.

Frequent mistakes

  • Saving the shared list instead of a copy.
  • Popping only on some return paths, for example returning early after a match and skipping the pop.
  • Treating a node with one child as a leaf.
  • Pruning when the running total exceeds the target, which drops valid paths when values can be negative.
  • Building a string of the path and splitting it later, which is slow and breaks on negative numbers or multi-digit values without a separator.

Follow-up questions

  • Paths may start and end at any node, going downward. Track prefix sums along the current branch in a counting map, and undo each entry on the way back up, the same backtracking rhythm applied to a map.
  • Only count the matching paths. Drop the path list and return counts from each subtree.
  • Return paths as strings such as 3->1->6. Join the saved values at the end rather than building strings during the walk.
  • Avoid recursion. Use an explicit stack of (node, remainder, path length) entries and trim the shared list back to the stored length before each append.

Explaining it out loud

Fictional example

A concise way to present it
Candidate
I'll do a depth-first walk with one list for the current path. I append the node, subtract its value from the remainder, and recurse into the children.
Candidate
At a leaf with remainder zero, I save a copy of the list, because I'm about to keep changing it. Before returning from any node, I pop it, so the list always matches the path from the root to where I am.
Candidate
The walk is linear. Copying matches costs up to the height each, so the worst case is n times h, which is unavoidable when the output is that large.

Path Sum is the yes-or-no version without the path list. Flatten Binary Tree to Linked List also follows preorder, but rewires the tree instead of recording it. Generate Parentheses uses the same append, recurse, remove rhythm on a string. Browse the coding problems hub for more.

Natively during practice

When you rehearse on Mac or Windows, Natively can read a tree problem like this from a screenshot and help you check that every append has a matching pop, or suggest a tree where two matching paths share a prefix. Your mock interview is transcribed and saved with notes, so you can reread the transcript and see whether you mentioned the copy before writing it. Details are on the AI interview assistant page.

Questions people ask

How do you solve Path Sum II?

Walk the tree depth first with one list for the current path. Append each node and subtract its value; at a leaf with a zero remainder, save a copy of the list; pop the node before returning.

Why do you need to copy the path in Path Sum II?

The path list keeps changing as the walk continues. Saving the list itself stores a reference, so every saved entry would end up as the same, usually empty, list.

What is the time complexity of Path Sum II?

The walk is O(n). Copying each match costs up to the tree's height, so the worst case is O(n·h), which is O(n²) for a degenerate tree.

What is the difference between Path Sum and Path Sum II?

Path Sum only asks whether a matching root-to-leaf path exists. Path Sum II returns every matching path, which adds the path list, backtracking and copying.

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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP