Q17: How do you perform Level Order Traversal (BFS) on a Binary Tree?
Use Breadth-First Search (BFS) with a Queue<TreeNode>. Offer root to queue. While queue is not empty, measure levelSize = queue.size(). Loop levelSize times to process nodes on the current level, polling nodes and offering non-null child nodes.
Level Order Traversal Solution
import java.util.*;
public class LevelOrder {
public static List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
currentLevel.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(currentLevel);
}
return result;
}
}💡 Uses queue snapshot sizes to partition nodes into level-by-level list arrays.
Key Takeaways
- BFS traversal utilizes a Queue data structure.
- Process levels in batches using snapshot level sizes (
queue.size()).
Knowledge Check
Why is recording levelSize = queue.size() BEFORE the level for-loop critical?