Average of Levels in Binary Tree
Easy
TreeBFS
Problem
Given the root of a binary tree, return the average value of nodes on each level as a list of doubles.
Example 1
Input: [3,9,20,null,null,15,7]
Output: [3.0, 14.5, 11.0]
Constraints
- 1 ≤ nodes ≤ 10⁴
Approach — Tree Traversal
This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time.
Solution code
Python
class Solution:
def averageOfLevels(self, root):
res = []
level = [root] if root else []
while level:
res.append(sum(n.val for n in level) / len(level))
level = [c for n in level for c in (n.left, n.right) if c]
return res
Java
import java.util.*;
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> out = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int sz = q.size();
double sum = 0;
for (int i = 0; i < sz; i++) {
TreeNode n = q.poll();
sum += n.val;
if (n.left != null) q.offer(n.left);
if (n.right != null) q.offer(n.right);
}
out.add(sum / sz);
}
return out;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Average of Levels in Binary Tree interactively → ← All solutions