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 targetSumtargetSum
Example 1
Output: [[5, 4, 11, 2], [5, 8, 4, 5]]
Example 2
Output: []
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.
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
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
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 pathSumwalk
- First,
creates the answer listpathSum and an empty listresult , and callspath on the root, withwalk as the amounttargetSum .remaining - In
, ifwalk isnode , the call returns at once, because there is nothing below to visit.null - Otherwise it adds
to the end ofnode.val and subtracts it frompath .remaining - If the node has no left and no right child and
is 0, it adds a copy ofremaining , made withpath , tonew ArrayList<>(path) . If not, it callsresult on the left child and then on the right child, passing the newwalk .remaining - Last, it removes the final value with
, sopath.remove(path.size() - 1) holds the parent's path again when the call returns.path
The class also has a small TreeNodebuildnullmain
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:
[[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]]walk[]
The third line, [][]walknull
The fifth line, [[-2, -3]][1, 2, 3]
Why the copy in step 4? With result.add(path)pathSum[[], []]
Complexity
The walk visits every node once, and each matching leaf also copies its path into the answer.
- Time: O(n × h), because
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.walk - Space: O(h) besides the answer, because the shared
list and the chain of unfinishedpath calls each hold one entry per level of the current path.walk
When the question is only whether such a path exists, the amount left over is enough and no list is needed: see