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).
root = [3,9,20,null,null,15,7][[3],[9,20],[15,7]]root = [1][[1]]root == null return []; else offer root to queuesz = queue.size() — nodes at the current levelsz nodes: collect values, enqueue non-null childrenres; loop until queue emptyA plain BFS queue mixes nodes from different levels — you can't tell where one level ends. By capturing sz = queue.size() before the inner loop, we freeze the count of nodes at the current level. No matter how many children get enqueued during the inner loop, we always process exactly sz nodes — giving a clean, isolated layer. This is the key insight of iterative BFS level order.
A normal depth-first traversal goes branch by branch, not level by level. You could carry the depth along and group the values afterwards, but there's a more natural tool.
Use a queue, which hands nodes back in the order they arrived. Before each level, read the queue's size: that is exactly how many nodes the level has. Pop that many nodes, record their values, and push their children for the next level.
Level by level means BFS with a queue. Read the queue size first, and that many nodes make one level.
Run the animation above on your own input, or watch the 1:47 video explanation of Binary Tree Level Order Traversal with a dry run and Java code.