Average of Levels in Binary Tree (LeetCode 637): Solution and Explanation
You get the root of a binary tree. For each level, from the root downward, compute the average of the values on that level and return the averages as a list.
Intuition
An average needs two numbers per level: the sum of its values and how many values there are. The task is really to group the nodes by level and keep those two numbers for each group.
A breadth-first search with a queue visits nodes in level order. The useful detail is that when you start a pass, the queue contains exactly the nodes of one level and nothing else, because the previous pass popped its whole level and only pushed the children.
So the queue length at the start of a pass is the level's count. Pop that many nodes, add their values, push their children, then divide. The children you pushed are the next level, ready for the next pass.
Approach: Breadth-first search, one level per pass
- Put the root in a queue and start with an empty result list.
- While the queue is not empty, record
size = len(queue)and setlevel_sum = 0. - Pop exactly
sizenodes. Add each value tolevel_sumand push its left and right children if they exist. - Append
level_sum / sizeto the result. - When the queue is empty, every level has been averaged; return the result.
Step-by-step example
root = [3,9,20,null,null,15,7]
- The queue starts as [3]. Size is 1: pop 3, level_sum = 3, push 9 and 20. Average 3 / 1 = 3.
- The queue is [9, 20]. Size is 2: pop 9 (no children), level_sum = 9; pop 20, level_sum = 29, push 15 and 7. Average 29 / 2 = 14.5.
- The queue is [15, 7]. Size is 2: pop both, level_sum = 22, no children. Average 22 / 2 = 11.
- The queue is empty. Return [3, 14.5, 11].
Code: Python, Java, C++
1class Solution:
2 def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
3 result = []
4 queue = deque([root])
5 while queue:
6 size = len(queue)
7 level_sum = 0
8 for _ in range(size):
9 node = queue.popleft()
10 level_sum += node.val
11 if node.left:
12 queue.append(node.left)
13 if node.right:
14 queue.append(node.right)
15 result.append(level_sum / size)
16 return result1class Solution {
2 public List<Double> averageOfLevels(TreeNode root) {
3 List<Double> result = new ArrayList<>();
4 Queue<TreeNode> queue = new ArrayDeque<>();
5 queue.offer(root);
6 while (!queue.isEmpty()) {
7 int size = queue.size();
8 long levelSum = 0;
9 for (int i = 0; i < size; i++) {
10 TreeNode node = queue.poll();
11 levelSum += node.val;
12 if (node.left != null) queue.offer(node.left);
13 if (node.right != null) queue.offer(node.right);
14 }
15 result.add((double) levelSum / size);
16 }
17 return result;
18 }
19}1class Solution {
2public:
3 vector<double> averageOfLevels(TreeNode* root) {
4 vector<double> result;
5 queue<TreeNode*> q;
6 q.push(root);
7 while (!q.empty()) {
8 int size = q.size();
9 long long levelSum = 0;
10 for (int i = 0; i < size; i++) {
11 TreeNode* node = q.front();
12 q.pop();
13 levelSum += node->val;
14 if (node->left) q.push(node->left);
15 if (node->right) q.push(node->right);
16 }
17 result.push_back((double) levelSum / size);
18 }
19 return result;
20 }
21};Time and space complexity
O(n)
Each node enters the queue once and leaves it once, and each pop does constant work.
O(w)
The queue holds at most two adjacent levels at once, which is O(w) where w is the widest level. For a full tree that is about n / 2 nodes.
Other approaches
DFS with per-depth sums and counts (time O(n), space O(h))
Walk the tree recursively, passing the depth. Keep two arrays indexed by depth, add the value to sums[depth] and 1 to counts[depth], then divide at the end. Same O(n) time, and the space is the recursion depth instead of the widest level.
Collect levels, then average (time O(n), space O(n))
Run a normal level-order traversal that returns a list of lists, then average each inner list. Simple to write, but it stores every value before computing anything.
Common mistakes
- Summing in a 32-bit int. Node values go up to 2^31 - 1, so two of them already overflow; use a long or 64-bit integer for the sum.
- Reading the queue length inside the loop instead of once before it. The queue grows as children are pushed, so the loop would spill into the next level.
- Using integer division. In Java, C++ and C#, cast the sum to double before dividing, or 29 / 2 becomes 14.
- Assuming the tree is complete. A level can be missing nodes anywhere, so count only the nodes actually popped.
Frequently asked questions
Why is the queue length the size of the current level?
Each pass pops the whole current level and only pushes children, which all belong to the next level. So when a new pass starts, everything in the queue sits on the same level.
Does the order of pushing left and right children matter?
Not for averages, since a sum does not depend on order. It only matters if you also need the values left to right, as in a level-order listing.
Is DFS or BFS better here?
Both are O(n). BFS matches the level structure directly. DFS uses less memory on wide, shallow trees and more on deep, narrow ones.
How precise does the answer need to be?
Answers within 10^-5 of the true average are accepted, so a normal double division is enough.