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 targetSumtargetSum
Example 1
Output: 3
Explanation: 5 ā 3, 5 ā 2 ā 1, and -3 ā 11.
Example 2
Output: 3
Explanation: 5 ā 4 ā 11 ā 2, 5 ā 8 ā 4 ā 5, and 4 ā 11 ā 7.
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 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
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 intintlong
Java Solution
The method pathSum
- First, create the map
, from running total to the number of nodes above with that total, and put total 0 into it with a count of 1.prefixCount - Then call the helper method
with the root, a running totalcount of 0 as asum , andlong astargetSum .target calls itself for each child, and a missing child returns 0 at once.count - In
, add the node's value tocount . Look upsum insum - target and keep its count inprefixCount : the number of paths that end at this node.paths - Add this node's total to the map with
, which adds 1 to the count, or stores 1 if the total is new. Then callmerge(sum, 1, Integer::sum) for the left and the right child and add their results tocount .paths - Finally, lower this node's count with
, so that other branches do not see it, and returnmerge(sum, -1, Integer::sum) .paths
The mainbuild
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:
3
3
0
5
1
0
Both examples print 3, one for each path listed under them. The empty tree gives 0, because countnull
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)
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 intint
Complexity
The walk visits each node once and does a fixed amount of map work there.
- Time: O(n), because
runs once for each of the n nodes and once for each missing child, and each run does one lookup and twocount calls, which take constant time on average.merge - 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