Trees & BST · Pattern 2 of 12

Backtracking on trees: root-to-leaf paths and path sums

Add the node to a shared path, recurse into both children, then remove it on the way back. The path always holds exactly the nodes from the root to where you are.

2 variations · 3 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Print or collect every root-to-leaf path
  • Paths whose values add up to a target
  • Paths that may start and end anywhere, as long as they go downward

The template

Backtracking
// Path Sum II: every root-to-leaf path that adds up to target
List<List<Integer>> pathSum(TreeNode root, int target) {
    List<List<Integer>> res = new ArrayList<>();
    dfs(root, target, new ArrayList<>(), res);
    return res;
}
void dfs(TreeNode node, int remain, List<Integer> path, List<List<Integer>> res) {
    if (node == null) return;
    path.add(node.val);                                       // choose
    remain -= node.val;
    if (node.left == null && node.right == null && remain == 0) res.add(new ArrayList<>(path));   // copy it
    dfs(node.left, remain, path, res);
    dfs(node.right, remain, path, res);
    path.remove(path.size() - 1);                             // un-choose on the way back
}

// Path Sum III: downward paths with sum target, using prefix sums of the current path
int countPaths(TreeNode root, int target) {
    Map<Long, Integer> seen = new HashMap<>();
    seen.put(0L, 1);                                          // the empty prefix
    return count(root, 0, target, seen);
}
int count(TreeNode node, long sum, int target, Map<Long, Integer> seen) {
    if (node == null) return 0;
    sum += node.val;
    int res = seen.getOrDefault(sum - target, 0);             // paths that end at this node
    seen.merge(sum, 1, Integer::sum);
    res += count(node.left, sum, target, seen) + count(node.right, sum, target, seen);
    seen.merge(sum, -1, Integer::sum);                        // undo before going back up
    return res;
}

The variations

  1. 1Collect every root-to-leaf path

    Push the node, record the path at a leaf (if it matches), recurse, pop. The pop is what makes one shared list work for every path.

    Now you solve
  2. 2Prefix sums along the current path

    A downward path from an ancestor to here has sum prefix(here) - prefix(ancestor). Keep counts of the prefix sums on the current path in a map, exactly like subarray sum equals k, and undo them when you return.

    Worked example Path Sum III Medium Read the solution

Mistakes to avoid

  • Adding path itself to the answer: it keeps changing. Add a copy.
  • Checking the target at a null child instead of at a real leaf: a node with one child is not a leaf, and each leaf gets counted twice.
  • Path Sum III: forgetting to undo the prefix count, so sums from another branch leak into this one.
Next: Level order traversal: BFS one level at a time →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.