Skip to content

Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

InputtargetSumOutputPath
[5,4,8,11,null,13,4,7,2,null,1]22true5→4→11→2
[1,2,3]5falseNo path sums to 5
  • The number of nodes is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
ApproachTimeSpaceBest When
DFS RecursiveO(n)O(h)Simple, clean code; h is height
BFS IterativeO(n)O(w)Avoid recursion; w is max width
★ Recommended

Use depth-first search. At each node, subtract its value from targetSum. Check if leaf and sum equals zero.

⏱ Time O(n) Visit each node once 💾 Space O(h) Recursion stack depth
function hasPathSum(root, targetSum):
if not root: return false
if not root.left and not root.right:
return root.val == targetSum
remaining = targetSum - root.val
return hasPathSum(root.left, remaining) or hasPathSum(root.right, remaining)
path_sum_dfs_recursive.py
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def hasPathSum(root: Optional[TreeNode], targetSum: int) -> bool:
"""
Check if tree has root-to-leaf path summing to targetSum using recursive DFS.
Time: O(n), Space: O(h) for recursion stack
"""
if not root:
return False
# Leaf node check
if not root.left and not root.right:
return root.val == targetSum
# Subtract current value and check left and right subtrees
remaining = targetSum - root.val
return hasPathSum(root.left, remaining) or hasPathSum(root.right, remaining)
# Test cases
if __name__ == "__main__":
# Example 1: [5,4,8,11,null,13,4,7,2,null,1], targetSum = 22
root = TreeNode(5)
root.left = TreeNode(4)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
root.right = TreeNode(8)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)
print(hasPathSum(root, 22)) # True
print(hasPathSum(root, 20)) # False
# Example 2: Single node
single = TreeNode(1)
print(hasPathSum(single, 1)) # True
print(hasPathSum(single, 2)) # False
alternative

Use a queue to track (node, current_sum) pairs. Process nodes level-by-level; check leaf when dequeued.

⏱ Time O(n) Visit each node once 💾 Space O(w) Queue size (max level width)
function hasPathSum(root, targetSum):
if not root: return false
queue = [(root, root.val)]
while queue:
node, currentSum = queue.pop()
if not node.left and not node.right and currentSum == targetSum:
return true
if node.left:
queue.push((node.left, currentSum + node.left.val))
if node.right:
queue.push((node.right, currentSum + node.right.val))
return false
path_sum_bfs_iterative.py
from typing import Optional
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def hasPathSum(root: Optional[TreeNode], targetSum: int) -> bool:
"""
Check if tree has root-to-leaf path summing to targetSum using iterative BFS.
Uses queue to store (node, current_sum) pairs.
Time: O(n), Space: O(w) where w is max width
"""
if not root:
return False
queue = deque([(root, root.val)])
while queue:
node, current_sum = queue.popleft()
# Check leaf node
if not node.left and not node.right and current_sum == targetSum:
return True
if node.left:
queue.append((node.left, current_sum + node.left.val))
if node.right:
queue.append((node.right, current_sum + node.right.val))
return False
# Test cases
if __name__ == "__main__":
# Example 1: [5,4,8,11,null,13,4,7,2,null,1], targetSum = 22
root = TreeNode(5)
root.left = TreeNode(4)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
root.right = TreeNode(8)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)
print(hasPathSum(root, 22)) # True
print(hasPathSum(root, 20)) # False
# Example 2: Single node
single = TreeNode(1)
print(hasPathSum(single, 1)) # True
print(hasPathSum(single, 2)) # False