mediumTreesPure DSA~20 min
Sum of All Root-to-Leaf Numbers
Each root-to-leaf path spells a number by concatenating digits (0-9) along the way. Sum the numbers formed by every root-to-leaf path.
Problem
Given the root of a binary tree where every node holds a single digit 0-9, each root-to-leaf path encodes a number. Return the total sum of all such numbers.
Input
A binary tree root with single-digit node values.
Output
An integer: the sum over all root-to-leaf numbers.
Constraints
- 1 <= number of nodes <= 1000
- 0 <= node value <= 9
- The total sum fits in a 32-bit integer.
Examples
Example 1
Input
root = [1,2,3]
Output
25
Paths form 12 and 13; 12 + 13 = 25.
Example 2
Input
root = [4,9,0,5,1]
Output
1026
495 + 491 + 40 = 1026.