Return the level order traversal of a binary tree.
This problem follows the BFS Queue pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Use a queue. Process all nodes at current level, add their children for next level.
Capturing queue size at the start of each iteration lets you process exactly one level at a time — this is the BFS level-order trick.
result = []
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)):
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 resultPractice Binary Tree Level Order Traversal and similar Trees problems with flashcards. Build pattern recognition through active recall.
Practice this problem