CodingNodes / Trees / Average of Levels in Binary Tree System design Space play · ←→ step · R restart

Problem

Given the root of a binary tree, return the average value of the nodes on each level, from the top level down. Answers within 1e-5 of the true value are accepted.

The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes ≤ 10000
  • -2^31 ≤ Node.val ≤ 2^31 − 1

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(w)

Time: Every node is added to the queue once and taken out once, with constant work each time.

Space: The queue holds at most one or two levels at a time, so it is as large as the widest level, w. That can reach n/2.

Use a queue so nodes come out level by level. At the start of each round the queue holds exactly one level, so save its size first. Take that many nodes, add their values, and queue their children for the next round. Then total divided by size is the level's average.