LeetCode 637: Average of Levels in Binary Tree is an Easy binary tree bfs problem. This Python walkthrough develops a level aggregation solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Binary Tree BFS |
| Reusable pattern | level aggregation |
| Complexity | O(n) time and O(w) space |
Recognizing the pattern
Breadth-first search is the natural fit when the answer is grouped by depth or depends on the first visit at a level.
For this problem specifically, for each BFS level, sum exactly its current queue length and divide by that length. The invariant worth writing beside the code is: Before moving to the next level, every node from the current level contributes once to its sum.
Step-by-step algorithm
- Identify the input state consumed by
averageOfLevels(root)and initialize the data required by the level aggregation pattern. - For each BFS level, sum exactly its current queue length and divide by that length.
- After each update, verify the page’s central invariant: Before moving to the next level, every node from the current level contributes once to its sum.
- Finish only after the boundary behavior is covered: Use numeric division; values may be negative.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
from collections import deque
class Solution:
def averageOfLevels(self, root):
queue, answer = deque([root]), []
while queue:
level_size = len(queue)
total = 0
for _ in range(level_size):
node = queue.popleft(); total += node.val
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
answer.append(total / level_size)
return answerReading the implementation
The main entry point is averageOfLevels(root). The named working state includes queue, level_size, total, node; those variables make the level aggregation state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, for each BFS level, sum exactly its current queue length and divide by that length.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. For each BFS level, sum exactly its current queue length and divide by that length. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so before moving to the next level, every node from the current level contributes once to its sum.
Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.
Complexity and trade-offs
O(n) time and O(w) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Depth-first search can carry an explicit depth and build the same result, but level boundaries are less direct. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().averageOfLevels(root)==[3.0,14.5,11.0]Common mistakes and edge cases
- Problem-specific boundary: Use numeric division; values may be negative.
- Pattern-level pitfall: Capture the current queue length before processing a level so children do not leak into the same batch.
- Invariant check: after every update, confirm that before moving to the next level, every node from the current level contributes once to its sum.
Interview review checklist
- Explain why level aggregation matches the structure of this input.
- State the invariant in one sentence before tracing code: Before moving to the next level, every node from the current level contributes once to its sum.
- Derive O(n) time and O(w) space from how many times each element or state is visited.
- Test the boundary explicitly: Use numeric division; values may be negative.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 199. Binary Tree Right Side View · Next: 102. Binary Tree Level Order Traversal