Sum Root to Leaf Numbers - Problem

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number. For example, the root-to-leaf path 1 → 2 → 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

A leaf node is a node with no children.

Input & Output

Example 1 — Simple Binary Tree
$ Input: root = [1,2,3]
Output: 25
💡 Note: Root-to-leaf paths: 1→2 gives number 12, and 1→3 gives number 13. Sum: 12 + 13 = 25
Example 2 — Deeper Tree
$ Input: root = [4,9,0,5,1]
Output: 1026
💡 Note: Root-to-leaf paths: 4→9→5 gives 495, 4→9→1 gives 491, 4→0 gives 40. Sum: 495 + 491 + 40 = 1026
Example 3 — Single Node
$ Input: root = [5]
Output: 5
💡 Note: Only one node, so the single root-to-leaf path is just 5

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

Visualization

Tap to expand
Sum Root to Leaf Numbers123Path: 1→2Number: 12Path: 1→3Number: 13Process:1. Find all root-to-leaf paths2. Convert each path to number3. Sum all numbersResult12 + 13 = 25
Understanding the Visualization
1
Input Tree
Binary tree with digits 0-9 as node values
2
Find Paths
Each root-to-leaf path forms a number (1→2 = 12, 1→3 = 13)
3
Sum Numbers
Add all root-to-leaf numbers together (12 + 13 = 25)
Key Takeaway
🎯 Key Insight: Build numbers incrementally during DFS traversal instead of storing all paths
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
182.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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