medium All Paths for a Sum
Problem Statement
Given a binary tree and a number ‘S’, find all paths from root-to-leaf such that the sum of all the node values of each path equals ‘S’.
Constraints:
- The number of nodes in the tree is in the range
[0, 5000]. -1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Try it yourself
Try solving this question here:
✅ Solution All Paths for a Sum
Problem Statement
Given a binary tree and a number ‘S’, find all paths from root-to-leaf such that the sum of all the node values of each path equals ‘S’.
Constraints:
- The number of nodes in the tree is in the range
[0, 5000]. -1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Solution
This problem follows the Binary Tree Path Sum problem. We can follow the same DFS approach. There will be two differences though:
Every time we find a root-to-leaf path, we will store it in a list. We will traverse all paths and will not stop processing after finding the first path.
Here is the visual representation of the algorithm:
Code
Here is the code for this algorithm:
import java.util.*;
// class TreeNode {
// int val;
// TreeNode left;
// TreeNode right;
// TreeNode(int x) {
// val = x;
// }
// };
class Solution {
public List<List<Integer>> findPaths(TreeNode root, int sum) {
List<List<Integer>> allPaths = new ArrayList<>();
List<Integer> currentPath = new ArrayList<Integer>();
findPathsRecursive(root, sum, currentPath, allPaths);
return allPaths;
}
private static void findPathsRecursive(
TreeNode currentNode,
int sum,
List<Integer> currentPath,
List<List<Integer>> allPaths
) {
if (currentNode == null) return;
// add the current node to the path
currentPath.add(currentNode.val);
// if the current node is a leaf and its value is equal to sum, save the current path
if (
currentNode.val == sum &&
currentNode.left == null &&
currentNode.right == null
) {
allPaths.add(new ArrayList<Integer>(currentPath));
} else {
// traverse the left sub-tree
findPathsRecursive(
currentNode.left,
sum - currentNode.val,
currentPath,
allPaths
);
// traverse the right sub-tree
findPathsRecursive(
currentNode.right,
sum - currentNode.val,
currentPath,
allPaths
);
}
// remove the current node from the path to backtrack,
// we need to remove the current node while we are going up the recursive call stack.
currentPath.remove(currentPath.size() - 1);
}
public static void main(String[] args) {
Solution sol = new Solution();
TreeNode root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(4);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
int sum = 23;
List<List<Integer>> result = sol.findPaths(root, sum);
System.out.println("Tree paths with sum " + sum + ": " + result);
}
}
Time Complexity
The time complexity of the above algorithm is
We can calculate a tighter time complexity of
Space Complexity
If we ignore the space required for the allPaths list, the space complexity of the above algorithm will be O(N) in the worst case. This space will be used to store the recursion stack. The worst-case will happen when the given tree is a linked list (i.e., every node has only one child).
How can we estimate the space used for the allPaths array? Take the example of the following balanced tree:
Here we have seven nodes (i.e., N = 7). Since, for binary trees, there exists only one path to reach any leaf node, we can easily say that total root-to-leaf paths in a binary tree can’t be more than the number of leaves. As we know that there can’t be more than allPaths will be allPaths list will be
From the above discussion, we can conclude that our algorithm’s overall space complexity is
Also, from the above discussion, since for each leaf node, in the worst case, we have to copy log(N) nodes to store its path; therefore, the time complexity of our algorithm will also be
Similar Problems
Problem 1: Given a binary tree, return all root-to-leaf paths.
Solution: We can follow a similar approach. We just need to remove the “check for the path sum.”
Problem 2: Given a binary tree, find the root-to-leaf path with the maximum sum.
Solution: We need to find the path with the maximum sum. As we traverse all paths, we can keep track of the path with the maximum sum.
🤖 Don't fully get this? Learn it with Claude
Stuck on All Paths for a Sum? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **All Paths for a Sum** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **All Paths for a Sum** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **All Paths for a Sum**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **All Paths for a Sum**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.