DSA AnimatorDSA animations
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.

How to solve Average of Levels in Binary Tree

LeetCode 637 · Easy · Tree · Pattern: BFS Level Order

Why the obvious approach is slow

You could first collect every node with its depth, group them by depth, and then average each group. That works, but it needs an extra map and a second pass. A breadth first search already visits the tree one level at a time, so we can average as we go.

The key idea

Use a queue, and start with just the root in it. At the start of each round, the queue holds exactly one full level. So read the queue size first, and that tells you how many nodes belong to this level. Pop exactly that many nodes, add up their values, and push their children for the next round. When the round ends, divide the sum by the count, and that is the average for this level.

Remember

The queue size at the start of a round is the size of that level. Use a double for the sum, so large values do not overflow.

Run the animation above on your own input, or watch the 2:35 video explanation of Average of Levels in Binary Tree with a dry run and Java code.

More Tree problems