FastPrepSum Root-to-Leaf Binary Numbers

Sum Root-to-Leaf Binary Numbers

Oracle logoOracle● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given the root of a binary tree whose node values are 0 or 1.

Each root-to-leaf path represents a binary number, with the root as its most significant bit. Return the sum of all represented numbers.

A leaf is a node with no children.

Function

sumRootToLeaf(root: TreeNode) → int

Examples

Example 1

root = [1,0,1,0,1,0,1]return = 22

The four paths represent 100, 101, 110, and 111, which sum to 22.

Example 2

root = [0]return = 0

The only path represents zero.

Example 3

root = [1]return = 1

The only path represents one.

Constraints

  • The tree contains between 1 and 1000 nodes.
  • node.val is 0 or 1.
  • The sum fits a signed 32-bit integer.

More Oracle problems

See Oracle hiring insights
public int sumRootToLeaf(TreeNode root) {
    // Write your code here.
}
root[1,0,1,0,1,0,1]
expected22
Checking account…