FastPrepSum Root-to-Leaf Numbers

Sum Root-to-Leaf Numbers

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given the root of a binary tree whose nodes each contain one digit from 0 through 9.

Every root-to-leaf path represents a number formed by reading its digits from the root to the leaf. Return the sum of all such numbers.

A leaf is a node with no children.

Function

sumNumbers(root: TreeNode) → int

Examples

Example 1

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

The paths form 12 and 13, whose sum is 25.

Example 2

root = [4,9,0,5,1]return = 1026

The paths form 495, 491, and 40, which sum to 1026.

Example 3

root = [0]return = 0

The only path consists of the digit 0.

Constraints

  • The tree contains between 1 and 1000 nodes.
  • 0 <= node.val <= 9.
  • The root has no leading-zero child-path ambiguity; a root value of 0 is allowed.
  • The sum of all represented numbers fits in a signed 32-bit integer.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int sumNumbers(TreeNode root) {
    // Write your code here.
}
root[1,2,3]
expected25
Checking account…