FastPrepAverage Values by Binary-Tree Level

Average Values by Binary-Tree Level

Motive logoMotive● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given the root of a non-empty binary tree, return an array whose value at index d is the arithmetic mean of all node values at depth d.

The root is at depth zero. Return averages from the root level down to the deepest level.

Function

averageOfLevels(root: TreeNode) → double[]

Examples

Example 1

root = [3,9,20,null,null,15,7]return = [3.0,14.5,11.0]

The three levels are [3], [9,20], and [15,7].

Example 2

root = [5]return = [5.0]

A one-node tree has one level.

Constraints

  • The tree contains 1 through 100000 nodes.
  • -1000000000 <= node.val <= 1000000000.
  • Answers within 1e-5 of the exact average are accepted.

More Motive problems

See Motive hiring insights
public double[] averageOfLevels(TreeNode root) {
    // write your code here
}
root[3,9,20,null,null,15,7]
expected[3.0,14.5,11.0]
Checking account…