Compute the sum of all numbers formed by root-to-leaf paths in a binary tree.
You are given the root of a binary tree where each node contains a single digit from 0 to 9.
Each root-to-leaf path represents a number formed by concatenating the digits along that path from top to bottom. Your task is to return the sum of all such numbers.
For example, if a path is 1 -> 2 -> 3, it represents the number 123.
Treat every root-to-leaf path independently and add up the values of all formed numbers.
Input Format
- The input is the root of a binary tree.
- Each node contains an integer digit in the range
0to9.
Output Format
- Return a single integer: the sum of all numbers represented by root-to-leaf paths.
Constraints
- The tree may be empty.
- Node values are digits from
0to9. - The answer fits in a 32-bit signed integer for typical interview constraints.
Example 1
Input
root = [1,2,3]
Output
25
Explanation
The root-to-leaf paths are 1→2 = 12 and 1→3 = 13. Their sum is 25.
Example 2
Input
root = [4,9,0,5,1]
Output
1026
Explanation
The paths are 4→9→5 = 495, 4→9→1 = 491, and 4→0 = 40. Total = 495 + 491 + 40 = 1026.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.