Does Any Root-to-Leaf Route Add Up to the Target
Solve this ProblemYou are given the root of a binary tree and an integer target. A route starts at the root, goes downward through children, and must end at a leaf (a node with no children). Return true if some route has node values that add up to exactly target, and false otherwise. An empty tree has no routes.
You can list the total of every route and check the list, or you can subtract each node's value from the target as you go down, so a leaf only needs to compare its own value with what remains.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ number of nodes ≤ 100 - ◆
−100 ≤ node.val ≤ 100; −1000 ≤ target ≤ 1000 - ◆
The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child - ◆
A route starts at the root, moves downward and must END at a leaf (a node with no children). Return true if the values along at least one such route add up to exactly target; an empty tree has no route
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Collect Every Route Total, Then Look for the Target
BruteWalk the whole tree once, carrying the running sum of the values on the way down. Each time a leaf is reached, append that route's total to a list. When the walk finishes, check whether the target appears in the list. It always visits every node (it cannot stop early even if the very first route already matches) and it stores one number per leaf, so time is O(n) and space is O(n) in the worst case.
O(n)O(n)1class Solution {
2 public boolean routeAddsUp(TreeNode root, int target) {
3 List<Integer> totals = new ArrayList<>();
4 collect(root, 0, totals);
5 return totals.contains(target);
6 }
7
8 private void collect(TreeNode node, int sum, List<Integer> totals) {
9 if (node == null) return;
10 sum += node.val;
11 if (node.left == null && node.right == null) {
12 totals.add(sum);
13 return;
14 }
15 collect(node.left, sum, totals);
16 collect(node.right, sum, totals);
17 }
18}Optimal — Count Down the Remaining Amount and Stop Early
OptimalInstead of adding up, subtract. Passing target − (this node's value) to the children means every child only has to find a route worth "what is still left". At a leaf the route is complete, so it succeeds exactly when the leaf's value equals the remaining amount. A missing child can never succeed. For an internal node, succeed if EITHER child does — and since || short-circuits, the search stops at the first successful route. Nothing is stored: O(h) space for the recursion, and O(n) time in the worst case (less when a route is found early).
O(n)O(h)1class Solution {
2 public boolean routeAddsUp(TreeNode root, int target) {
3 if (root == null) return false;
4 if (root.left == null && root.right == null) return root.val == target;
5 int remaining = target - root.val;
6 return routeAddsUp(root.left, remaining) || routeAddsUp(root.right, remaining);
7 }
8}