Path Sum (LeetCode 112): Solution and Explanation
You are given the root of a binary tree and a target number. Decide whether some path that starts at the root and ends at a leaf has node values adding up exactly to that target.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force idea is to list every root-to-leaf path, add up each one, and compare the totals with the target. That works, but building and storing whole paths is wasted effort, because the only thing you ever need from a path is its running sum.
So carry the sum down with you instead. A neat trick is to carry the remaining amount rather than the accumulated amount: every time you step onto a node, subtract its value from the target. When you reach a leaf, the question collapses to a single comparison, whether the remaining target equals that leaf's value.
This turns the problem into a plain depth-first search where each call asks a smaller version of the same question: does the left subtree or the right subtree contain a root-to-leaf path that sums to what is left? The or between the two recursive calls also gives you early exit for free, because Python stops evaluating as soon as the left side returns true.
The one subtle part is the definition of a leaf. A path has to end at a node with no children, so a node with only one child is never a valid endpoint even if the running sum matches there. Handling the empty tree as false and checking the target only at real leaves covers every case.
Approach: Recursive DFS with target reduction
- If the current node is
None, return false, since an empty subtree contains no path. - If the node has no left and no right child, it is a leaf, so return whether
targetSum == root.val. - Otherwise subtract the node's value from
targetSumto get the amount the rest of the path must supply. - Recurse into the left child with the reduced target, and if that fails, recurse into the right child.
- Return true as soon as either subtree reports a matching path, and false if neither does.
Step-by-step example
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
- At the root 5, it is not a leaf, so the remaining target becomes 22 minus 5, which is 17.
- Go left to 4, not a leaf, so the remaining target becomes 17 minus 4, which is 13.
- Go left to 11, not a leaf, so the remaining target becomes 13 minus 11, which is 2.
- Go left to the leaf 7. The check is 2 == 7, which is false, so this branch fails.
- Back at 11, try the right child, the leaf 2. The check is 2 == 2, which is true.
- The true value bubbles up through 11, 4 and 5 without exploring the right half of the tree, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
3 if not root:
4 return False
5
6 if not root.left and not root.right:
7 return targetSum == root.val
8
9 targetSum -= root.val
10 return (self.hasPathSum(root.left, targetSum) or
11 self.hasPathSum(root.right, targetSum))1class Solution {
2 public boolean hasPathSum(TreeNode root, int targetSum) {
3 if (root == null) return false;
4
5 if (root.left == null && root.right == null) {
6 return targetSum == root.val;
7 }
8
9 return hasPathSum(root.left, targetSum - root.val) ||
10 hasPathSum(root.right, targetSum - root.val);
11 }
12}1class Solution {
2public:
3 bool hasPathSum(TreeNode* root, int targetSum) {
4 if (!root) return false;
5
6 if (!root->left && !root->right) {
7 return targetSum == root->val;
8 }
9
10 return hasPathSum(root->left, targetSum - root->val) ||
11 hasPathSum(root->right, targetSum - root->val);
12 }
13};Time and space complexity
O(n)
Each node is visited at most once, and the work per node is a constant number of comparisons and one subtraction, so the total is linear in the number of nodes.
O(h)
The recursion stack holds one frame per level of the current path, so it grows to the tree height h. That is O(log n) for a balanced tree and O(n) for a tree shaped like a linked list.
Other approaches
Iterative DFS with a stack (time O(n), space O(h))
Push pairs of (node, remaining target) onto an explicit stack and pop them one by one, checking leaves as you go. It does the same work as the recursion but avoids Python's recursion limit on very deep, skewed trees.
BFS with running sums (time O(n), space O(w))
Walk the tree level by level with a queue that stores each node together with the sum of the path from the root to it. It finds shallow matching leaves quickly but keeps a whole level in memory, which can be up to half the nodes.
Common mistakes
- Checking the target at every node instead of only at leaves. For the tree [1,2] with target 1, the root alone sums to 1, but it has a child, so the correct answer is false.
- Returning true for an empty tree when the target is 0. An empty tree has no root-to-leaf path at all, so the answer must be false.
- Pruning a branch as soon as the running sum exceeds the target. Node values can be negative, so a sum that overshoots can still come back down to the target further along the path.
- Treating a node with exactly one child as a leaf. Only nodes with both children missing can end a path.
Frequently asked questions
Why is the time complexity of Path Sum O(n)?
In the worst case no path matches, so the search has to visit every node once before returning false. Each visit does constant work, which gives O(n) overall.
Can you solve Path Sum without recursion?
Yes. Use an explicit stack or queue that stores each node alongside the remaining target. Pop a pair, check whether it is a leaf with a matching value, and push its children with the reduced target. The complexity stays the same.
Should Path Sum use BFS or DFS?
Both are correct. DFS is the natural fit because it follows one path at a time and its memory is bounded by the height. BFS can find a shallow answer sooner, but its queue may hold an entire level of the tree.
Does the path have to start at the root?
Yes. In this problem the path must start at the root and end at a leaf. Paths that can start and end anywhere are a different, harder problem that is usually solved with prefix sums.