Imagine you have a binary tree where each node contains a single digit from 0 to 9. This tree represents multiple numbers formed by following paths from the root to each leaf node.
For example, if you have a path that goes 1 โ 2 โ 3, this represents the number 123. Your task is to find all such root-to-leaf paths and return the sum of all numbers they represent.
Goal: Calculate the total sum of all numbers formed by root-to-leaf paths in the binary tree.
Input: The root node of a binary tree containing digits 0-9
Output: An integer representing the sum of all root-to-leaf numbers
Input & Output
Visualization
Time & Space Complexity
Visit each node exactly once in the tree
Recursion stack depth equals tree height h, O(log n) for balanced tree
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
- All test cases guarantee the answer fits in a 32-bit integer