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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code