Average of Levels in Binary Tree
LeetCode 637 · Easy · solution, intuition & step-by-step walkthrough
BFS with level size; average per level.
This is how I solved Average of Levels in Binary Tree (LeetCode 637), an easy problem from the Tree pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Level-order BFS processes one level at a time: sum the values of the nodes in the current queue snapshot and divide by how many there are.
Approach
- 1
Queue with the root.
- 2
For each level, pop size nodes, sum values, enqueue children.
- 3
Append sum / size.
How I solved it
Level-order BFSPythonO(n) time
class Solution:
def averageOfLevels(self, root):
queue = [root]
res = []
while queue:
size = len(queue)
total = 0
for i in range(size):
node = queue.pop(0)
if node is None:
continue
total += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(total / size)
return resAverage of Levels in Binary Tree — FAQ
What is the intuition behind Average of Levels in Binary Tree?
Level-order BFS processes one level at a time: sum the values of the nodes in the current queue snapshot and divide by how many there are.
How do you solve Average of Levels in Binary Tree (LeetCode 637)?
1. Queue with the root. 2. For each level, pop size nodes, sum values, enqueue children. 3. Append sum / size.
What is the time and space complexity of Average of Levels in Binary Tree?
Time: O(n). Space: O(n). (Accepted approach: Level-order BFS.)
What are common mistakes in Average of Levels in Binary Tree?
Use floating-point division.