Skip to content

Sum Root to Leaf Numbers

You are given the root of a binary tree containing digits from 0-9 only. Each root-to-leaf path represents a number. Return the total sum of all numbers represented by root-to-leaf paths.

InputOutputCalculation
[1,2,3]2512 + 13
[4,9,0,5,1]1026495 + 491 + 40
  • The number of nodes is in the range [1, 1000].
  • 0 <= Node.val <= 9
ApproachTimeSpaceBest When
DFSO(n)O(h)Simple, clean; h is height
BFSO(n)O(w)Avoid recursion; w is max width
★ Recommended

Recursively traverse with current_sum multiplied by 10 and incremented by current digit. Sum leaf values.

⏱ Time O(n) Visit each node once 💾 Space O(h) Recursion depth
sum_root_to_leaf_numbers_dfs.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 sumNumbers(root: Optional[TreeNode]) -> int:
"""
Sum all root-to-leaf numbers using DFS.
Build number by appending digits as we traverse down.
Time: O(n), Space: O(h) for recursion stack
"""
def dfs(node, current_sum):
if not node:
return 0
# Build number: multiply by 10 and add current digit
current_sum = current_sum * 10 + node.val
# Leaf node: return the complete number
if not node.left and not node.right:
return current_sum
# Recursively process children and sum
return dfs(node.left, current_sum) + dfs(node.right, current_sum)
return dfs(root, 0)
# Test cases
if __name__ == "__main__":
# Example 1: [1,2,3]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(sumNumbers(root)) # 25 (12 + 13)
# Example 2: [4,9,0,5,1]
root2 = TreeNode(4)
root2.left = TreeNode(9)
root2.right = TreeNode(0)
root2.left.left = TreeNode(5)
root2.left.right = TreeNode(1)
print(sumNumbers(root2)) # 1026 (495 + 491 + 40)
# Example 3: Single node
single = TreeNode(0)
print(sumNumbers(single)) # 0
alternative

Use a queue with (node, current_number) pairs. Sum all leaf numbers encountered.

⏱ Time O(n) Visit each node once 💾 Space O(w) Queue size (max width)
sum_root_to_leaf_numbers_bfs.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 sumNumbers(root: Optional[TreeNode]) -> int:
"""
Sum all root-to-leaf numbers using iterative BFS.
Queue stores (node, current_number) pairs.
Time: O(n), Space: O(w) where w is max width
"""
if not root:
return 0
queue = deque([(root, root.val)])
total = 0
while queue:
node, current_sum = queue.popleft()
# Leaf node: add to total
if not node.left and not node.right:
total += current_sum
continue
if node.left:
queue.append((node.left, current_sum * 10 + node.left.val))
if node.right:
queue.append((node.right, current_sum * 10 + node.right.val))
return total
# Test cases
if __name__ == "__main__":
# Example 1: [1,2,3]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print(sumNumbers(root)) # 25 (12 + 13)
# Example 2: [4,9,0,5,1]
root2 = TreeNode(4)
root2.left = TreeNode(9)
root2.right = TreeNode(0)
root2.left.left = TreeNode(5)
root2.left.right = TreeNode(1)
print(sumNumbers(root2)) # 1026 (495 + 491 + 40)
# Example 3: Single node
single = TreeNode(0)
print(sumNumbers(single)) # 0