Binary Tree Level Order Traversal — Step-by-Step Visualization
mediumLeetCode #102TreeBreadth-First SearchBinary Tree
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
Algorithm Pattern
Breadth-First Search (BFS)
Key Idea
To traverse a tree level-by-level, we use a Queue. For each level, we record the queue's size, process that many nodes, and add their children to the queue for the next level. This ensures we finish one level before moving to the next.
Step-by-Step Approach
- Initialize a queue with the `root` node.
- While the queue is not empty, calculate the current level's size.
- Iterate `size` times: pop a node from the queue, add its value to the `currentLevel` list, and push its children (if they exist) back into the queue.
- After the inner loop finishes, add `currentLevel` to the final results.
Common Gotchas
- Don't forget to check if the root is null at the beginning.
- The 'level size' snapshot is key—it prevents the inner loop from accidentally processing nodes added for the next level.