Level Averages

Level Averages

Return the average value of the nodes on each level, top to bottom, as a slice of float64.

levelAverages(root)

Input format: level-order with x for missing children. Output the averages space-separated (e.g. 3 14.5 11).

Examples

3 9 20 x x 15 7   // → [3, 14.5, 11]
1 2 3              // → [1, 2.5]
(empty)            // → []

Walkthrough

Thinking it through

This extends level-grouping: instead of collecting each level's raw values, you want one summary number per level — the average. You don't need to keep every value around, just a running sum and count.

Reusing the level-boundary trick

The same invariant applies: at the start of each round, the queue's length tells you exactly how many nodes belong to the level about to be processed, since children enqueued during a round belong to the next level. That size becomes your count directly — no separate counting pass.

Building the algorithm

  1. Seed the queue with the root, if the tree isn't empty.
  2. At the start of each round, record the queue's length as this level's count.
  3. Dequeue exactly that many nodes, adding each value to a running sum, and enqueue their children.
  4. Divide the sum by the count for this level's average, and record it.
  5. Repeat until the queue empties.

Why you don't need to store the level's values as a list first

You could reuse the level-grouping solution to build value lists per level, then loop over each computing sum and average afterward. That works, but it holds an entire list per level just to collapse it into one number. Since sum and count are exactly what an average needs, and both accumulate incrementally as you dequeue, there's no need to materialize the list at all.

Why the division must produce a real (non-integer-truncated) number

An average of integers usually isn't an integer. The division needs to preserve fractional results, or a level like [9, 20] would incorrectly report 14 instead of 14.5.

Cost

Every node is still enqueued and dequeued once, so work is proportional to the number of nodes; the per-level sum and count add no meaningful overhead.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.