Problem · Tree
Sum Root-to-Leaf Numbers
Learn this problemProblem statement
You are given the root of a binary tree. Every node stores one decimal digit from 0 through 9. Each root-to-leaf path represents the number formed by reading its digits from root to leaf.
Return the sum of the numbers represented by all root-to-leaf paths. A leaf has no children. Return 0 for an empty tree.
Follow-up
How can an iterative traversal avoid call-stack overflow on a very deep tree?
Function
sumNumbers(root: TreeNode) → intExamples
Example 1
root = [1,2,3]return = 25The paths form 12 and 13, whose sum is 25.
Example 2
root = [4,9,0,5,1]return = 1026The paths form 495, 491, and 40.
Example 3
root = []return = 0An empty tree has no root-to-leaf paths.
Constraints
- Each node value is between
0and9. - The tree may be empty.
- The final sum fits in a signed
32-bit integer.