Sum Root to Leaf Numbers - Problem

Imagine you have a binary tree where each node contains a single digit from 0 to 9. This tree represents multiple numbers formed by following paths from the root to each leaf node.

For example, if you have a path that goes 1 โ†’ 2 โ†’ 3, this represents the number 123. Your task is to find all such root-to-leaf paths and return the sum of all numbers they represent.

Goal: Calculate the total sum of all numbers formed by root-to-leaf paths in the binary tree.

Input: The root node of a binary tree containing digits 0-9

Output: An integer representing the sum of all root-to-leaf numbers

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [1,2,3]
โ€บ Output: 25
๐Ÿ’ก Note: Root-to-leaf paths are 1->2 (forms number 12) and 1->3 (forms number 13). Sum: 12 + 13 = 25
example_2.py โ€” Deeper Tree
$ Input: root = [4,9,0,5,1]
โ€บ Output: 1026
๐Ÿ’ก Note: Root-to-leaf paths: 4->9->5 (495), 4->9->1 (491), and 4->0 (40). Sum: 495 + 491 + 40 = 1026
example_3.py โ€” Single Node
$ Input: root = [9]
โ€บ Output: 9
๐Ÿ’ก Note: Single node tree has only one root-to-leaf path containing just 9

Visualization

Tap to expand
Family Tree Phone Directory1Grandpa: 12Parent: 123Parent: 134Child: 1245Child: 125Phone Numbers Found:โ€ข Path 1โ†’2โ†’4: Phone = 124โ€ข Path 1โ†’2โ†’5: Phone = 125โ€ข Path 1โ†’3: Phone = 13Total Sum: 124 + 125 + 13 = 262Algorithm Steps:1. Start DFS with number = 02. At each node: number = number ร— 10 + digit3. At leaf: add complete number to sum4. Backtrack and continue with siblings5. Return total sum of all phone numbers
Understanding the Visualization
1
Start at the Root
Begin at the eldest ancestor with phone number starting as 0
2
Build Number Incrementally
As you move to each descendant, multiply current number by 10 and add their digit
3
Collect at Leaf Nodes
When you reach someone with no children, you have a complete phone number
4
Sum All Numbers
Add all collected phone numbers to get the final sum
Key Takeaway
๐ŸŽฏ Key Insight: Instead of collecting all paths first, we build each number incrementally during DFS traversal and sum them immediately at leaf nodes, achieving optimal O(n) time complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Visit each node exactly once in the tree

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h, O(log n) for balanced tree

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • 0 โ‰ค Node.val โ‰ค 9
  • The depth of the tree will not exceed 10
  • All test cases guarantee the answer fits in a 32-bit integer
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
89.0K Views
High Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen