Problem 258
Sum of Root-to-Leaf Numbers
Medium · 20 pts · Tree, Binary Tree, Depth-First Search
Problem
Every node of a binary tree holds a single digit from 0 to 9. Each path from the root down to a leaf spells a number when you read its digits from top to bottom; for example, the path 1 → 2 → 3 spells 123. Print the sum of the numbers spelled by all root-to-leaf paths, modulo 1000000007. Traverse the tree while carrying the number built so far: moving to a child turns current into current × 10 + child's digit. At a leaf, add the current number to the total. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child.
Output
Print the sum modulo 1000000007.
Constraints
1 <= number of nodes <= 10000; 0 <= value <= 9
Example input
3 1 2 3
Example output
25
Explanation
The root 1 has two leaf children, 2 and 3. The paths spell 12 and 13, and their sum is 12 + 13 = 25.