Path Sum
Check whether some path from the root of a binary tree down to a leaf adds up to a target number.
Given the root of a binary tree and an integer targetSumtargetSum
Example 1
Output: true
Explanation: 5 → 4 → 11 → 2.
Example 2
Output: false
Explanation: the paths sum to 3 and 4.
Example 3
Output: false
Explanation: an empty tree has no paths at all.
The Idea
Think of the tree in Example 1 as a trail that splits as you walk down. You start at the top node, 5, which is called the root. At every node you step down to one of its children, until you reach a node with no children, a leaf. The root 5 has two children, 4 and 8. The leaves are 7, 2, 13 and 1.
So Example 1 has four walks from the root to a leaf. The walk 5, 4, 11, 7 adds up to 27, and 5, 4, 11, 2 adds up to 22. The walk 5, 8, 13 gives 26, and 5, 8, 4, 1 gives 18. One of them reaches 22, so the answer is true.
Adding up each walk on its own repeats work, though. The walks to 7 and to 2 share 5, 4 and 11, so those three numbers get added twice. Can we carry what we already know down the tree instead of starting over for each leaf?
We can, if we carry the amount still needed instead of a running total. The target is 22. After taking 5, the rest of the walk must still bring 17. After 4, it must bring 13, and after 11, only 2. Look at the picture below.
The orange walk goes 5, 4, 11, 2. Each node is labelled with what it still needs, and the leaf 2 reads "needs 0": the walk has used up the whole target, so it is a match. The leaf 7 next to it reads "needs -5", because 7 overshoots the 2 that was still needed.
The labels also show something about the question itself. At node 11, the question "does a walk from the root reach 22?" has turned into "does a walk from 11 down to a leaf reach 2?". That is the same problem on a smaller tree, the one hanging below 11.
A method can answer such a question by calling itself on the smaller tree, which is called recursion. It follows one branch all the way down to a leaf before it tries the next one. Searching a tree in that order is called depth-first search, or DFS.
Solution Approach
Turning the amount still needed into a recursive method means comparing it with the simple way of listing every path, then settling three things: what each call passes to the children, where the comparison with the target happens, and when the search may stop.
Listing every path first
Why not collect every root-to-leaf path and add each one up? That works, but it keeps whole paths in memory, and nodes near the root get added once for every leaf below them. Carrying the amount still needed does each subtraction once per node.
Passing the amount still needed
What does a node hand to its children? It subtracts its own value from the amount it received and passes the result to both children. The root receives targetSum
Checking only at a leaf
Where should the amount be compared with zero? Only at a leaf, because the problem asks for paths that end at a leaf. In the tree [1, 2]
A missing child is not a leaf either. When a call reaches a child that does not exist, there is no path through it, so that call answers false.
When the search can stop
Can the search stop once the amount still needed drops below zero? Not here, because node values can be negative. In the tree [-2, null, -3]
The search can stop as soon as one side finds a match, though. If the left child's subtree answers true, the right child's subtree does not need to be searched at all.
Java Solution
The method hasPathSum
- First, if
isroot , return false. This covers an empty tree, as in Example 3, and a missing child below a node.null - Subtract the node's value from
and keep the result intargetSum , the amount the rest of the path must still add.remaining - If the node has no left child and no right child, it is a leaf. Return whether
is exactly 0.remaining - Otherwise, call
on the left child withhasPathSum , then on the right child, joined withremaining . Java skips the right call when the left call already returned true.||
The program also has a small TreeNodebuildnullrun
The main
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
public class PathSum {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public static boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false; // no node here, so no path either
}
int remaining = targetSum - root.val; // what the rest of the path must add
if (root.left == null && root.right == null) {
return remaining == 0; // a leaf: the path ends here
}
return hasPathSum(root.left, remaining) || hasPathSum(root.right, remaining);
}
// Builds a tree from its 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> parents = new ArrayDeque<>();
parents.add(root);
int i = 1;
while (i < values.length) {
TreeNode parent = parents.poll();
if (values[i] != null) {
parent.left = new TreeNode(values[i]);
parents.add(parent.left);
}
i++;
if (i < values.length && values[i] != null) {
parent.right = new TreeNode(values[i]);
parents.add(parent.right);
}
i++;
}
return root;
}
static void run(Integer[] values, int targetSum) {
boolean found = hasPathSum(build(values), targetSum);
System.out.println(Arrays.toString(values) + ", target " + targetSum + " -> " + found);
}
public static void main(String[] args) {
run(new Integer[] {5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1}, 22);
run(new Integer[] {1, 2, 3}, 5);
run(new Integer[] {}, 0);
run(new Integer[] {1, 2}, 1);
run(new Integer[] {-2, null, -3}, -5);
run(new Integer[] {5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1}, 26);
}
}
Running it prints:
[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], target 22 -> true
[1, 2, 3], target 5 -> false
[], target 0 -> false
[1, 2], target 1 -> false
[-2, null, -3], target -5 -> true
[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], target 26 -> true
Look at the fourth line, [1, 2], target 1 -> false
That line is where a tempting shortcut goes wrong. Suppose the leaf test is dropped, and the nulltargetSum == 0[1, 2], target 1 -> true
The fifth line, [-2, null, -3], target -5 -> true
Complexity
Each call does one subtraction and one leaf test, so the cost comes from how many calls run and how many wait on each other at once.
- Time: O(n), because when no path matches,
runs once for each of the n nodes, plus once for each missing child of a node that has only one child.hasPathSum - Space: O(h), because the calls still waiting are the nodes on the path from the root to the current node, at most h of them, where h is the number of nodes on the tree's longest root-to-leaf path.
To list every path that reaches the target instead of answering yes or no, see