Generation Averages

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

A lab grows a cell culture from one starting cell. Each cell splits into at most two daughter cells. The lab records the family as a binary tree: every node holds a cell's size in micrometres, and its children are the cells it split into.

To spot whether cells shrink over time, the lab wants the average size of each generation: the starting cell, then its daughters, then 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 just 12. Generation 2 is 8 and 10, average 9. Generation 3 is 7, 9 and 15 (the null is a missing cell), average 31 / 3 = 10.333…

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

A single starting cell that never split: one generation, 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

Do a depth-first walk, passing the depth along, and keep a sum and a count per depth in two lists. Then divide.

That is actually O(n) and perfectly fine. It is listed here because it is a natural first idea. The breadth-first version matches the question more directly: "per level" is exactly what BFS 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