← Back to DSA Animator
Average of Levels in Binary Tree LC #637 Easy BFS · Level Average
Problem

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [3.0, 14.5, 11.0]
Explanation: L1: 3/1=3.0  |  L2: (9+20)/2=14.5  |  L3: (15+7)/2=11.0
Example 2
Input: root = [1,2,3,4,5]
Output: [1.0, 2.5, 4.5]
Example 3
Input: root = [1]
Output: [1.0]
Constraints: 0 ≤ nodes ≤ 104  |  −231 ≤ Node.val ≤ 231 − 1
Try Examples
Custom:
Approach
BFS with Level Snapshot — Accumulate Sum
Before each level, snapshot sz = queue.size(). Sum all sz node values, then compute avg = sum / sz. The snapshot ensures we only sum nodes from the current level.
Binary Tree
Level 1
Level 2
Level 3
Level 4+
In Queue
Processing
BFS Queue
Queue is empty
Level Statistics
No levels processed yet…
Variables
Level #
sz (snapshot)
sum (running)
avg
Method Call Trace
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Offer root to queue; create empty result list
2
Snapshot sz = queue.size() — node count at current level; init sum = 0
3
Poll exactly sz nodes: sum += node.val, enqueue non-null children
4
Compute avg = sum / sz, add to result; loop until queue empty
Time
O(n)
Space
O(n)
Why Level Snapshot Works

Extending level order BFS — instead of collecting values, we accumulate a running sum. By capturing sz = queue.size() before the inner loop, we guarantee sum contains exactly the current level's nodes. avg = sum / sz gives the level average. Without the snapshot, children added during iteration would corrupt the level boundary and inflate the sum.