Path Sum
Path Sum is a easy trees & bst problem solved with the recursion pattern.
The best approach, iterative dfs (stack of node and running sum), runs in O(n) time and O(h) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (collect every path sum, then search) up.
Problem
Given the root of a binary tree and an integer targetSum, decide whether the tree has a root-to-leaf path whose node values add up to exactly targetSum. Return true if at least one such path exists, and false otherwise.
A path starts at the root and goes down one child at a time until it reaches a leaf, a node with no children. An empty tree has no paths, so the answer for it is always false.
Examples
Example 1
- Input
root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], targetSum = 22- Output
true- Why
- The path 5 → 4 → 11 → 2 ends at a leaf and adds up to 22. The other paths give 27, 26 and 18.
Example 2
- Input
root = [1, 2, 3], targetSum = 5- Output
false- Why
- The two root-to-leaf paths add up to 1 + 2 = 3 and 1 + 3 = 4. Neither is 5.
Example 3
- Input
root = [1, 2], targetSum = 1- Output
false- Why
- The root alone sums to 1, but it is not a leaf: it has a left child. The only root-to-leaf path is 1 → 2, which sums to 3.
Constraints
- The number of nodes is in the range
[0, 5000]. -1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 18 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (collect every path sum, then search) | O(n · h) | O(n · h) |
| Recursive DFS (subtract on the way down) | O(n) | O(h) |
| Iterative DFS (stack of node and running sum) | O(n) | O(h) |
1Brute force (collect every path sum, then search)
O(n · h)Every node copies a path of length up to h, the height of the tree; summing each leaf's path costs the same again.O(n · h)Each call on the stack holds its own copy of the path.List every root-to-leaf path explicitly. Walk the tree, building a fresh copy of the path at every node, and at each leaf add up the values of its path and store the total. At the end, check whether the target is among the stored totals. It works, but it copies and re-adds whole paths.
- DFS from the root carrying a list
path; at each node make a new listpath + [node.val]. - At a leaf, add up its list and store the total in
sums. - Return whether
targetSumis insums(false when the tree is empty).
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
List<Integer> sums = new ArrayList<>();
collect(root, new ArrayList<>(), sums);
return sums.contains(targetSum);
}
private void collect(TreeNode node, List<Integer> path, List<Integer> sums) {
if (node == null) return;
List<Integer> next = new ArrayList<>(path);
next.add(node.val);
if (node.left == null && node.right == null) {
int total = 0;
for (int v : next) total += v;
sums.add(total);
return;
}
collect(node.left, next, sums);
collect(node.right, next, sums);
}
}class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
sums = []
self.collect(root, [], sums)
return targetSum in sums
def collect(self, node: Optional[TreeNode], path: List[int], sums: List[int]) -> None:
if node is None:
return
nxt = path + [node.val]
if node.left is None and node.right is None:
sums.append(sum(nxt))
return
self.collect(node.left, nxt, sums)
self.collect(node.right, nxt, sums)class Solution {
void collect(TreeNode* node, vector<int> path, vector<int>& sums) {
if (!node) return;
path.push_back(node->val);
if (!node->left && !node->right) {
int total = 0;
for (int v : path) total += v;
sums.push_back(total);
return;
}
collect(node->left, path, sums);
collect(node->right, path, sums);
}
public:
bool hasPathSum(TreeNode* root, int targetSum) {
vector<int> sums;
collect(root, {}, sums);
return find(sums.begin(), sums.end(), targetSum) != sums.end();
}
};function hasPathSum(root, targetSum) {
const sums = [];
collect(root, [], sums);
return sums.includes(targetSum);
}
function collect(node, path, sums) {
if (node === null) return;
const next = [...path, node.val];
if (node.left === null && node.right === null) {
sums.push(next.reduce((a, b) => a + b, 0));
return;
}
collect(node.left, next, sums);
collect(node.right, next, sums);
}2Recursive DFS (subtract on the way down)
O(n)Each node is visited at most once with O(1) work.O(h)The recursion goes as deep as the height h: O(log n) for a balanced tree, O(n) for a list-shaped one.There is no need to remember the path, only how much of the target is still missing. Each call subtracts its node's value from the target and passes the rest to its children. At a leaf the question becomes: is the remaining amount exactly the leaf's value? A null child means there is no path in that direction, so it answers false. The answer for a node is the left answer OR the right answer, and OR stops as soon as one side succeeds.
- If
rootis null, return false. - If
rootis a leaf, returntargetSum == root.val. - Otherwise let
rest = targetSum - root.val. - Return
hasPathSum(root.left, rest) || hasPathSum(root.right, rest).
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return targetSum == root.val;
int rest = targetSum - root.val;
return hasPathSum(root.left, rest) || hasPathSum(root.right, rest);
}
}class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None:
return targetSum == root.val
rest = targetSum - root.val
return self.hasPathSum(root.left, rest) or self.hasPathSum(root.right, rest)class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return targetSum == root->val;
int rest = targetSum - root->val;
return hasPathSum(root->left, rest) || hasPathSum(root->right, rest);
}
};function hasPathSum(root, targetSum) {
if (root === null) return false;
if (root.left === null && root.right === null) return targetSum === root.val;
const rest = targetSum - root.val;
return hasPathSum(root.left, rest) || hasPathSum(root.right, rest);
}3Iterative DFS (stack of node and running sum)
O(n)Each node is pushed and popped once.O(h)A DFS stack holds at most about two nodes per level, so O(h) pairs (a BFS queue would hold up to a whole level instead).The same search without recursion. Push pairs of (node, sum of the path from the root down to and including that node) on an explicit stack. Pop a pair; if the node is a leaf and its sum equals the target, the answer is true. Otherwise push each existing child with the sum plus the child's value. If the stack empties, no leaf matched. Using a queue instead of a stack gives a level-by-level (BFS) version with the same result.
- If
rootis null, return false. - Push
(root, root.val)onto two parallel stacks, one for nodes and one for sums. - Pop
(node, sum). If node is a leaf andsum == targetSum, return true. - Push
(node.right, sum + node.right.val)and(node.left, sum + node.left.val)for the children that exist. - When the stack is empty, return false.
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
Deque<TreeNode> nodes = new ArrayDeque<>();
Deque<Integer> sums = new ArrayDeque<>();
nodes.push(root);
sums.push(root.val);
while (!nodes.isEmpty()) {
TreeNode node = nodes.pop();
int sum = sums.pop();
if (node.left == null && node.right == null && sum == targetSum) return true;
if (node.right != null) {
nodes.push(node.right);
sums.push(sum + node.right.val);
}
if (node.left != null) {
nodes.push(node.left);
sums.push(sum + node.left.val);
}
}
return false;
}
}class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
stack = [(root, root.val)]
while stack:
node, s = stack.pop()
if node.left is None and node.right is None and s == targetSum:
return True
if node.right is not None:
stack.append((node.right, s + node.right.val))
if node.left is not None:
stack.append((node.left, s + node.left.val))
return Falseclass Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
vector<pair<TreeNode*, int>> stack;
stack.push_back({root, root->val});
while (!stack.empty()) {
auto [node, sum] = stack.back();
stack.pop_back();
if (!node->left && !node->right && sum == targetSum) return true;
if (node->right) stack.push_back({node->right, sum + node->right->val});
if (node->left) stack.push_back({node->left, sum + node->left->val});
}
return false;
}
};function hasPathSum(root, targetSum) {
if (root === null) return false;
const stack = [[root, root.val]];
while (stack.length > 0) {
const [node, sum] = stack.pop();
if (node.left === null && node.right === null && sum === targetSum) return true;
if (node.right !== null) stack.push([node.right, sum + node.right.val]);
if (node.left !== null) stack.push([node.left, sum + node.left.val]);
}
return false;
}Edge cases to test
- Empty tree: there is no path at all, so the answer is false even when the target is 0
- A single node: true exactly when its value equals the target
- A node with one child is not a leaf, so a running sum that matches there does not count
- Negative values: a partial sum can go past the target and come back, so you cannot stop early when the sum gets too big
- A very deep, list-shaped tree (recursion depth up to 5000)
Hints
Hint 1
A path only counts if it ends at a leaf, a node with no children.
Hint 2
Instead of carrying the sum so far, carry what is still needed: subtract each node's value on the way down.
Hint 3
At a leaf, the answer is simply whether the amount still needed equals the leaf's value. Combine the two subtrees with OR.
FAQ
What is the best time complexity for Path Sum?
Iterative DFS (stack of node and running sum) runs in O(n) time and O(h) extra space. Each node is pushed and popped once.
Which pattern does Path Sum use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Path Sum?
Yes. Brute force (collect every path sum, then search) takes O(n · h) time and O(n · h) space. List every root-to-leaf path explicitly.
Which edge cases should I test for Path Sum?
Empty tree: there is no path at all, so the answer is false even when the target is 0; A single node: true exactly when its value equals the target; A node with one child is not a leaf, so a running sum that matches there does not count; Negative values: a partial sum can go past the target and come back, so you cannot stop early when the sum gets too big; A very deep, list-shaped tree (recursion depth up to 5000).