Path Sum II

Find every path from the root down to a leaf whose values add up to a target number.

Given the root of a binary tree and a number targetSum, return every path that starts at the root, ends at a leaf, and whose values add up to targetSum. A leaf is a node with no children. Return each path as the list of its values from the root down. The paths can come in any order.

Example 1
Input: root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], targetSum = 22
Output: [[5, 4, 11, 2], [5, 8, 4, 5]]
Example 2
Input: root = [1, 2, 3], targetSum = 5
Output: []
Solution

The Idea

Think of the tree as trails that branch out downhill from one starting point. Every trail ends at a spot where it cannot go any further, and we want the trails whose numbers add up to 22.

Example 1 writes its tree row by row, top to bottom and left to right, with null where a child is missing. So 5 is the root, and 4 and 8 are its children. Then 11 is the left child of 4, and the null after it says that 4 has no right child.

Look at the picture below. It draws that tree, which has five leaves at the bottom ends: 7, 2, 13, 5 and 1. Each leaf ends exactly one path from the root, so there are five paths to check. Under each leaf is what is left over when you start from 22 and subtract every value on the way down.

The tree from Example 1 with target 22. Each leaf shows what is left over after subtracting the values on its path. The orange path 5, 4, 11, 2 and the teal path 5, 8, 4, 5 leave 0; the leaves 7, 13 and 1 leave -5, -4 and 4.

Follow the orange path: 22 minus 5, 4, 11 and 2 leaves 0, so the path 5, 4, 11, 2 adds up to 22. The teal path 5, 8, 4, 5 also ends with left over 0. The leaves 7, 13 and 1 end with left over -5, -4 and 4, so their paths miss. In Example 2, the tree [1, 2, 3] has two paths, 1, 2 and 1, 3, which add up to 3 and 4, so the answer is empty.

Counting down from 22 is the easy half. To say whether some path works, the amount left over is all you need. Here the answer must also list the values, and the orange and teal paths share the root 5. Do we need a separate list for every path we try?

No. Walk the tree with one list that always holds the values from the root down to where you stand. Stepping down to a child adds its value to the end, and stepping back up removes it. At a leaf with left over 0, the list holds exactly that path, so we save a copy of it.

Solution Approach

Turning the one-list walk into code means settling three things: how to reach every leaf, when a path counts, and how one shared list can replace a new list at each node.

Reaching every leaf

How do we reach every leaf along with its path? A method that calls itself on the left child and then on the right child reaches every node. It goes all the way down one side before it tries the other, an order called depth-first search.

Each call receives the amount still left over, subtracts its own node's value, and passes the new amount to both children. A missing child arrives as null, and the call for it simply returns, which ends that branch.

When a path counts

When is a path finished? Only at a leaf, a node whose left and right children are both missing. Take the tree [1, 2] with target 1: the root alone adds up to 1, but it has the child 2, so it is not a leaf and the path 1 does not count.

The walk also keeps going when the amount left over drops below 0, because node values may be negative. A later negative value can bring the amount back up to exactly 0.

One list for every path

Why not give each call its own copy of the path so far? That works, but every node then copies all the values above it, which costs time and memory at every level. One shared list is enough if each call cleans up after itself.

A call adds its node's value to the end of the list, lets both children work, and then removes that last value. When it returns, the list is back to its parent's path, ready for the parent's other child. Making a choice, exploring from it and then undoing it is called backtracking.

Because the list keeps changing after a leaf is saved, the saved entry must be a copy of the list, not the list itself.

Java Solution

The method pathSum and its helper walk work in these steps:

  1. First, pathSum creates the answer list result and an empty list path, and calls walk on the root, with targetSum as the amount remaining.
  2. In walk, if node is null, the call returns at once, because there is nothing below to visit.
  3. Otherwise it adds node.val to the end of path and subtracts it from remaining.
  4. If the node has no left and no right child and remaining is 0, it adds a copy of path, made with new ArrayList<>(path), to result. If not, it calls walk on the left child and then on the right child, passing the new remaining.
  5. Last, it removes the final value with path.remove(path.size() - 1), so path holds the parent's path again when the call returns.

The class also has a small TreeNode class and a build helper that makes a tree from the row-by-row form, with null for a missing child. The main method runs both examples, the tree [1, 2] with target 1, an empty tree, a tree with negative values, and a tree where two different paths hold the same values.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class PathSumII {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> result = new ArrayList<>();
        walk(root, targetSum, new ArrayList<>(), result);
        return result;
    }

    private static void walk(TreeNode node, int remaining, List<Integer> path,
                             List<List<Integer>> result) {
        if (node == null) {
            return;
        }
        path.add(node.val);
        remaining -= node.val;
        if (node.left == null && node.right == null && remaining == 0) {
            result.add(new ArrayList<>(path));   // copy: path keeps changing
        } else {
            walk(node.left, remaining, path, result);
            walk(node.right, remaining, path, result);
        }
        path.remove(path.size() - 1);            // step back to the parent's path
    }

    // Builds a tree from the row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = queue.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                queue.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                queue.add(parent.right);
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(pathSum(build(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1), 22));
        System.out.println(pathSum(build(1, 2, 3), 5));
        System.out.println(pathSum(build(1, 2), 1));
        System.out.println(pathSum(build(), 0));
        System.out.println(pathSum(build(-2, null, -3), -5));
        System.out.println(pathSum(build(1, 2, 2, 3, null, null, 3), 6));
    }
}

Running it prints:

Output
[[5, 4, 11, 2], [5, 8, 4, 5]]
[]
[]
[]
[[-2, -3]]
[[1, 2, 3], [1, 2, 3]]

Look at [[5, 4, 11, 2], [5, 8, 4, 5]] on the first line: the orange path from the picture comes before the teal one, because walk tries the left child before the right. The second line, [], is Example 2.

The third line, [], is the tree [1, 2] with target 1, where the root alone adds up to 1 but is not a leaf. The empty tree on the fourth line gives [] as well, since walk returns at once on a null root.

The fifth line, [[-2, -3]], comes from a root -2 whose only child is a right child -3, with target -5. After the root, the amount left over is -3, below 0, and the value -3 still brings it to 0. The last line lists [1, 2, 3] twice. The tree [1, 2, 2, 3, null, null, 3] has one such path down each side, and each one is a separate path.

Why the copy in step 4? With result.add(path) instead, every saved entry is the same list object, and by the time pathSum returns, each call has removed its value from it. A version changed that way prints [[], []] for Example 1: two entries, as expected, but both empty.

Complexity

The walk visits every node once, and each matching leaf also copies its path into the answer.

  • Time: O(n × h), because walk does fixed work at each of the n nodes, and each of up to about n / 2 matching leaves copies up to h values, h being the number of levels.
  • Space: O(h) besides the answer, because the shared path list and the chain of unfinished walk calls each hold one entry per level of the current path.

When the question is only whether such a path exists, the amount left over is enough and no list is needed: see Path Sum.