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 targetSum, return true if some path that starts at the root and goes down to a leaf has values adding up to targetSum. A leaf is a node with no children. If no such path exists, return false.

Example 1
Input: root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], targetSum = 22
Output: true
Explanation: 5 → 4 → 11 → 2.
Example 2
Input: root = [1, 2, 3], targetSum = 5
Output: false
Explanation: the paths sum to 3 and 4.
Example 3
Input: root = [], targetSum = 0
Output: false
Explanation: an empty tree has no paths at all.
Solution

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 tree of Example 1 with target 22. Next to each node is what is still needed below it: 5 needs 17, 4 needs 13, 11 needs 2. The leaf 2 needs 0, a match. The leaves 7, 13 and 1 need -5, -4 and 4.

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 itself, so in Example 1 the 5 passes 17 down to 4 and to 8.

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] with target 1, the root alone already reaches 1. It still has the child 2, so the only root-to-leaf path is 1, 2, which adds up to 3.

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] with target -5, the root -2 leaves -3 still needed, and the leaf -3 brings it to exactly 0.

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 works in these steps:

  1. First, if root is null, return false. This covers an empty tree, as in Example 3, and a missing child below a node.
  2. Subtract the node's value from targetSum and keep the result in remaining, the amount the rest of the path must still add.
  3. If the node has no left child and no right child, it is a leaf. Return whether remaining is exactly 0.
  4. Otherwise, call hasPathSum on the left child with remaining, then on the right child, joined with ||. Java skips the right call when the left call already returned true.

The program also has a small TreeNode class and a build helper. It turns the row-by-row form of the examples, with null for a missing child, into linked nodes. The run helper prints each input, its target and the answer.

The main method runs the three examples, a root that matches the target but is not a leaf, a tree of negative values, and Example 1 again with the target 26.

Java
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:

Output
[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. The root 1 alone matches the target, but it has the child 2, so it is not a leaf and the comparison never runs there. The method only compares at the leaf 2, where the amount still needed is -2.

That line is where a tempting shortcut goes wrong. Suppose the leaf test is dropped, and the null case returns targetSum == 0 instead of false. Then the missing right child of 1 counts as the end of a path. We ran that version on the same tree, and it prints [1, 2], target 1 -> true.

The fifth line, [-2, null, -3], target -5 -> true, is the tree of negative values from above: after -2 the amount still needed is -3, below zero, and the leaf -3 still completes the path. The last line finds 26 on the right side of Example 1, through 5, 8 and 13.

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, hasPathSum runs once for each of the n nodes, plus once for each missing child of a node that has only one child.
  • 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 Path Sum II.