Generation Averages

Easybreadth-first searchAlso known as Average of Levels in Binary Tree

A lab grows a cell culture from one starting cell, and each cell splits into at most two daughters. The family is a binary tree whose nodes hold cell sizes in micrometres. To see whether cells shrink over time, the lab wants the average size of each generation: the starting cell, its daughters, theirs, and so on.

Your task

Write generationAverages(root). Return a list with the average node value of each level of the tree, from the top level down.

An empty tree gives an empty list. Trees are shown in level order, like [12, 8, 10, 7, 9, null, 15], where null marks a missing child. Your function receives real TreeNode objects with val, left and right.

generationAverages(root: TreeNode) → float[] Numbers are accepted within 1e-6.

Examples

Example 1
Input
root = [12, 8, 10, 7, 9, null, 15]
Output
[12, 9, 10.333333333333334]
Why

Generation 1 is the single cell 12. Generation 2 is 8 and 10, which average 9. Generation 3 is 7, 9 and 15 (null is a missing cell), which average 31 / 3 = 10.333…

Example 2
Input
root = [5]
Output
[5]
Why

The one cell never split, so there is a single generation with average 5.

Constraints

  • 0 ≤ number of cells ≤ 10,000
  • -1,000,000 ≤ size ≤ 1,000,000
  • Answers within 0.000001 of the expected value are accepted.
Start with brute force

A depth-first walk that passes the depth along and keeps a sum and a count for each depth is also O(n) and works well. Breadth-first search matches the question more directly, because it gives you one level at a time.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code