Easy
Binary Tree Level Order
👶 The 5-Year-Old Summary
Visit a tree level by level! First the grandparents, then parents, then children! Like taking an elevator that stops at each floor!
🎮 Interactive Visualizer
Breadth-First Search (BFS) with a queue!
Queue:
Result Levels:
🧠The Brain Hack
Use a QUEUE! Add root to queue. While queue not empty, process all items in queue (that's one level!), add their children for next level!
💻 The Clean Solution
from collections import deque
def level_order(root):
if not root: return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
result.append(level)
return result
# Tree: 3
# / \
# 9 20
# / \
# 15 7
# Result: [[3], [9, 20], [15, 7]]
Time: O(n)
Space: O(w) - max width