Path Sum III

Count the downward paths in a binary tree whose values add up to a target.

Given the root of a binary tree and a number targetSum, count the paths whose values add up to targetSum. A path may start and end at any node, but it must go downward, from parent to child.

Example 1
Input: root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], targetSum = 8
Output: 3
Explanation: 5 → 3, 5 → 2 → 1, and -3 → 11.
Example 2
Input: root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], targetSum = 22
Output: 3
Explanation: 5 → 4 → 11 → 2, 5 → 8 → 4 → 5, and 4 → 11 → 7.
Solution

The Idea

Think of the tree as a set of trails that split as they go down. In Example 1, the root 10 sits at the top, and its two children, 5 and -3, sit below it. The 5 has children of its own, 3 and 2, and so on down to the bottom row. A path is any stretch of a trail that only goes down, such as 5 → 2 → 1. It does not have to start at the root or end at the bottom.

Which stretches add up to 8? There are three: 5 → 3, 5 → 2 → 1 and -3 → 11. One way to find them is to start at every node and walk down from it, adding as you go. But could a single node tell, on its own, how many good stretches end at it?

Walk down from the root and keep a running total: the sum of all values from the root to where you stand. Look at the picture below. Beside each node, the label "total" gives its running total: 10 at the root, 15 at 5, 17 at 2, and 18 at 1.

The tree of Example 1 with the running total from the root beside each node. Node 1 has total 18 and node 10 has total 10. 18 minus the target 8 is 10, so the path 5, 2, 1 below node 10 adds up to 8.

The stretch 5 → 2 → 1 is the walk from the root to node 1, with the root left off. So its sum is the total at node 1 minus the total at node 10: 18 āˆ’ 10 = 8. Turned around, a stretch ending at node 1 adds up to 8 exactly when a node above it has total 18 āˆ’ 8 = 10. Node 10 has that total, so one stretch ends at node 1, and it starts just below node 10.

The other two answers show up the same way. The 3 just under node 5 and the 11 under -3 also have total 18, and each finds the total 10 at the root above it. So every node only has to ask one question: how many nodes above it have a running total equal to its own total minus the target? A running total like this, the sum from the start up to some point, is called a prefix sum.

Solution Approach

Running totals replace a simpler but slower way, walking down from every node. Using them means four decisions: how to remember the totals above a node, count paths that start at the root, forget totals from other branches, and choose the number type for a total.

Walking down from every node

Why not start at each node and add up every downward stretch from it? It gives the right count, but a node is then visited again for every node above it. In a tree where each node has only one child, a chain of n nodes, that is about n²/2 steps. With running totals, one walk from the root is enough.

Remembering the totals above a node

How does a node find out how many nodes above it have a given total? Keep a hash map, named prefixCount, from a running total to the number of nodes above with that total. A count is needed, not just yes or no, because several nodes can share a total. When a node's value is 0, for example, it has the same total as its parent. Looking up one total in a hash map takes a single step on average.

Paths that start at the root

What about a path that starts at the root itself? In Example 2, 5 → 4 → 11 → 2 adds up to 22 and starts at the root 5. At node 2 the total is 22, so it looks for 22 āˆ’ 22 = 0, and no node has total 0. The fix is to put total 0 into the map once before the walk starts, standing for the empty spot above the root.

Forgetting totals from other branches

Which totals may a node look at? Only those of the nodes above it, on its own trail from the root. The walk goes all the way down one branch, comes back up, and then goes down the next one, which is called depth-first search. So when the walk has finished a node and everything below it, it lowers the count of that node's total in the map by one.

Take the tree [1, 2, 3] with target 1: the root 1 has a left child 2 and a right child 3, with totals 1, 3 and 4. Node 3 looks for 4 āˆ’ 1 = 3. That total belongs to node 2, which is on the other branch, so it must be gone from the map by then. Otherwise it would count a path from node 2 to node 3, which does not exist.

Holding a total in a long

Can a running total grow too big? Node values are ints, and a trail of many large values can add up past what an int can hold. The total then wraps around to a wrong value, which might match a total in the map by chance. Keeping the total in a long, which goes up to about 9 Ɨ 1018, avoids that.

Java Solution

The method pathSum works in these steps:

  1. First, create the map prefixCount, from running total to the number of nodes above with that total, and put total 0 into it with a count of 1.
  2. Then call the helper method count with the root, a running total sum of 0 as a long, and targetSum as target. count calls itself for each child, and a missing child returns 0 at once.
  3. In count, add the node's value to sum. Look up sum - target in prefixCount and keep its count in paths: the number of paths that end at this node.
  4. Add this node's total to the map with merge(sum, 1, Integer::sum), which adds 1 to the count, or stores 1 if the total is new. Then call count for the left and the right child and add their results to paths.
  5. Finally, lower this node's count with merge(sum, -1, Integer::sum), so that other branches do not see it, and return paths.

The main method builds each tree from the row-by-row form of the examples with a small helper, build. It runs both examples, an empty tree, a tree of three zeros, the tree [1, 2, 3] with target 1, and a chain of five large values with target 0.

Java
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;

public class PathSumIII {

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

    public static int pathSum(TreeNode root, int targetSum) {
        Map<Long, Integer> prefixCount = new HashMap<>(); // running totals on the current path
        prefixCount.put(0L, 1);                            // the empty start above the root
        return count(root, 0L, targetSum, prefixCount);
    }

    private static int count(TreeNode node, long sum, int target,
                             Map<Long, Integer> prefixCount) {
        if (node == null) {
            return 0;
        }
        sum += node.val;                                   // running total from the root
        int paths = prefixCount.getOrDefault(sum - target, 0); // paths ending here
        prefixCount.merge(sum, 1, Integer::sum);
        paths += count(node.left, sum, target, prefixCount);
        paths += count(node.right, sum, target, prefixCount);
        prefixCount.merge(sum, -1, Integer::sum);          // leaving this node: take it back
        return paths;
    }

    // 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(10, 5, -3, 3, 2, null, 11, 3, -2, null, 1), 8));
        System.out.println(pathSum(build(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1), 22));
        System.out.println(pathSum(build(), 0));
        System.out.println(pathSum(build(0, 0, 0), 0));
        System.out.println(pathSum(build(1, 2, 3), 1));
        int a = 858993459;
        System.out.println(pathSum(build(a, a, null, a, null, a, null, a + 1), 0));
    }
}

Running it prints:

Output
3
3
0
5
1
0

Both examples print 3, one for each path listed under them. The empty tree gives 0, because count returns at once when the root is null.

Look at the fourth line, 5. It comes from [0, 0, 0] with target 0: each of the three nodes alone adds up to 0, and so do the root with its left child and the root with its right child. At either child, the map holds total 0 with a count of 2, once for the empty spot above the root and once for the root. That is why the map keeps counts.

The fifth line, 1, is the tree [1, 2, 3] with target 1, where only the root alone adds up to 1. A run of the same method without the line merge(sum, -1, Integer::sum) printed 2, because node 3 found node 2's total 3.

The last line, 0, is the chain. Its first four nodes hold 858,993,459 and the last holds 858,993,460, so the total at the bottom is 4,294,967,296, which is 232. No path adds up to 0. A run with an int total instead printed 1: the int wraps to exactly 0 at the bottom node and matches the 0 put in at the start.

Complexity

The walk visits each node once and does a fixed amount of map work there.

  • Time: O(n), because count runs once for each of the n nodes and once for each missing child, and each run does one lookup and two merge calls, which take constant time on average.
  • Space: O(n), because the map keeps a key for every different total it has seen, up to n + 1, and the recursion goes as deep as the tree is tall, which is n for a chain.

Running totals find stretches of an array with a given sum in the same way: see Subarray Sum Equals K.