Path Sum Validation in Binary Trees
Trees & GraphsModel answerLast updated
Determine whether any root-to-leaf path in a binary tree sums to a given target value.
Problem
You are given a binary tree and an integer target_sum. Your task is to determine whether there exists any complete path from the root to a leaf node where the sum of all node values along that path equals target_sum.
Return True if such a path exists, otherwise return False.
Definitions
- A leaf node has no children (both
leftandrightareNone) - A root-to-leaf path is a sequence of nodes starting from the root and ending at a leaf
- An empty tree (where
rootisNone) contains no paths
Function Signature
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def has_path_sum(root: TreeNode | None, target_sum: int) -> bool:
pass
Input Constraints
- Number of nodes: 0 to 5,000
- Node values: -1,000 to 1,000
- Target sum: -100,000 to 100,000
Examples
Example 1:
Tree:
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
target_sum = 22
Output: True
Explanation: The path 5 → 4 → 11 → 2 has sum 22
Example 2:
Tree:
1
/
2
target_sum = 1
Output: False
Explanation: Node 1 has a child, so it's not a leaf. The only complete path is 1 → 2, which sums to 3
Example 3:
Tree: (empty)
target_sum = 0
Output: False
Explanation: No paths exist in an empty tree
Important Notes
- Nodes with exactly one child are not leaf nodes
- Node values can be negative, so path sums may increase or decrease
- An empty tree always returns
False, even whentarget_sumis 0
Hints
Hint 1
Track the remaining sum needed as you traverse down rather than accumulating the total
Hint 2
Remember that only nodes with no children count as leaves—a node with one child must be traversed further
Hint 3
Consider using an iterative approach with a stack to avoid recursion depth limits in deeply skewed trees
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Path Sum Validation
Approach
The core insight is to transform this from an "accumulate upward" problem into a "track downward" problem. Instead of summing values as we go, we subtract each node's value from the target and check if we reach zero exactly at a leaf.
Algorithm:
- Start at the root with the full
target_sumas our remaining target - At each node, subtract its value from the remaining target
- When we reach a leaf (both children are
None), check if the remaining target is zero - If not at a leaf, continue traversing to all children with the updated remaining target
- Return
Trueif any leaf satisfies the condition
The key correctness principle: at any node n with remaining value r, we know that r = target_sum - (sum of all values from root to n's parent). This invariant holds throughout the traversal.
Why This Works
Every root-to-leaf path corresponds to exactly one leaf node. By visiting every node in the tree exactly once, we examine every possible path. The path sum equals target_sum if and only if, when we subtract all node values along the way, we arrive at a leaf with zero remaining.
For the empty tree case: no nodes means no leaves, so False is correct regardless of the target.
Implementation Details
Iterative vs Recursive: The iterative approach with an explicit stack is preferred in production Python code. The recursive solution is elegant but hits Python's default recursion limit (~1,000 frames) on deeply skewed trees. With up to 5,000 nodes allowed, a fully linear tree would cause a stack overflow.
Leaf Detection:
A critical detail is checking node.left is None and node.right is None. A node with exactly one child is not a leaf and must not trigger the sum check. This is what makes Example 2 return False.
Complexity Analysis
- Time: O(n) where n is the number of nodes. Each node is visited exactly once.
- Space: O(h) where h is tree height. The stack/recursion depth grows with height, not node count.
- Best case (balanced): O(log n)
- Worst case (skewed): O(n)
Code
def has_path_sum(root: TreeNode | None, target_sum: int) -> bool:
if root is None:
return False
# Stack entries: (current_node, remaining_target_before_this_node)
stack = [(root, target_sum)]
while stack:
node, remaining = stack.pop()
remaining -= node.val
# Check if this is a leaf
if node.left is None and node.right is None:
if remaining == 0:
return True
continue
# Add children to stack (only if they exist)
if node.right is not None:
stack.append((node.right, remaining))
if node.left is not None:
stack.append((node.left, remaining))
return False
Recursive alternative (mention the depth limitation if asked):
def has_path_sum(root, target_sum):
if root is None:
return False
if root.left is None and root.right is None:
return root.val == target_sum
new_target = target_sum - root.val
return has_path_sum(root.left, new_target) or has_path_sum(root.right, new_target)
Common Pitfalls
- Empty tree with target 0: Returning
Truehere is wrong—there are no paths at all - Checking sum at non-leaf nodes: This accepts incomplete paths
- Early termination when sum exceeds target: Values can be negative, so overshooting doesn't mean the path is invalid
- Treating single-child nodes as leaves: Example 2 specifically tests this
- Recursion in Python without discussing depth: Always mention the 1,000-frame limit for production code
Extensions
Returning all matching paths:
Maintain a current_path list and append each node's value during traversal. At matching leaves, save a copy of the path. Remember to remove the node when backtracking (or use tuples in the stack for the iterative version).
DFS vs BFS: Both work. DFS (stack) uses O(h) space, while BFS (queue) can use O(w) space where w is maximum width (up to n/2 for balanced trees). Choose DFS for deep trees, BFS if matching paths are likely shallow.
Very deep trees:
The iterative solution shown handles this naturally. Recursive solutions would need sys.setrecursionlimit(), which is fragile and can crash the interpreter.