Sum Root-to-Leaf Node Values
Problem statement
You are given the root of a nonempty binary tree whose nodes contain digit values. For each root-to-leaf path, add the values of its nodes. Return the sum of these path sums across every root-to-leaf path.
Each path contributes its node values directly. Do not interpret the path as a multi-digit decimal number. A leaf is a node with no children.
Function
sumRootToLeafValues(root: TreeNode) → intExamples
Example 1
root = [1,2,3]return = 7The two root-to-leaf path sums are 1 + 2 = 3 and 1 + 3 = 4, for a total of 7.
Example 2
root = [4,9,0,5,1]return = 36The three path sums are 4 + 9 + 5 = 18, 4 + 9 + 1 = 14, and 4 + 0 = 4. Their total is 36.
Example 3
root = [9]return = 9The root is also the only leaf, so its single path contributes 9.
Constraints
- The tree has between
1and1000nodes. - Each node value is an integer from
0through9. - The tree depth is at most
10.