FastPrepSum Root-to-Leaf Node Values

Sum Root-to-Leaf Node Values

Meta logoMeta● MediumFULLTIMEONSITE INTERVIEW
Learn

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) → int

Examples

Example 1

root = [1,2,3]return = 7

The 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 = 36

The 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 = 9

The root is also the only leaf, so its single path contributes 9.

Constraints

  • The tree has between 1 and 1000 nodes.
  • Each node value is an integer from 0 through 9.
  • The tree depth is at most 10.

More Meta problems

See Meta hiring insights
public int sumRootToLeafValues(TreeNode root) {
    // Write your code here
}
root[1,2,3]
expected7
Checking account…