Average of Levels in Binary Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #637
Given the root of a binary tree, return the average value of the nodes on each level, as an array. Answers within 10⁻⁵ of the true value are accepted.
Examples
text
[3,9,20,null,null,15,7] → [3.0, 14.5, 11.0]
[3,9,20,15,7] → [3.0, 14.5, 11.0]Hints
- This is level-order traversal again: process
len(queue)nodes at a time.
Approach
Run BFS level by level, sum the values, and divide by the level size. In languages with fixed-width integers, add up the sum in a 64-bit integer or a double. Node values can be up to 2³¹−1, so a 32-bit sum would overflow.
Complexity
Time: O(n). Space: O(w).
Python solution
def averageOfLevels(root):
out, level = [], [root] if root else []
while level:
out.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 outJavaScript solution
function averageOfLevels(root) {
const out = [];
let level = root ? [root] : [];
while (level.length) {
out.push(level.reduce((s, n) => s + n.val, 0) / level.length);
const next = [];
for (const n of level) { if (n.left) next.push(n.left); if (n.right) next.push(n.right); }
level = next;
}
return out;
}