Visualize Breadth-First Search on a Binary Tree: a level-order traversal that visits nodes level by level using a queue.
About this algorithm
Level-order traversal visits a binary tree one level at a time: the root, then its children from left to right, then their children. It is breadth-first search on a tree, and it is the natural way to answer questions about depth, such as the shallowest leaf, the rightmost node on each level, or how wide the tree gets.
Use level order when the answer depends on how far a node is from the root: the minimum depth, the nodes you would see from the right side, printing a tree row by row, or linking each node to its neighbour on the same level. Pick a depth-first order (pre-order, in-order or post-order) when the answer is built from whole subtrees, such as a subtree sum or height, or when you need sorted output from a binary search tree. DFS also needs less memory on a wide, shallow tree, because it only holds one root-to-leaf path at a time.
Start with a queue holding only the root. An empty tree gives an empty result.
Remove the node at the front of the queue and add its value to the output.
If the node has a left child, add it to the back of the queue, then do the same for the right child. Children always join behind everything already waiting, so a whole level leaves the queue before any node of the next level does.
Each node enters and leaves the queue exactly once. To group the output by level, read the queue's length at the start of each round and take exactly that many nodes before starting the next group.
The page loads a tree with root 0, children 1 (left) and 2 (right), then 3 as the left child of 1 and 4 as the right child of 2. The queue starts as [0]. Take 0 and queue 1 and 2: [1, 2]. Take 1 and queue its left child 3: [2, 3]. Take 2 and queue its right child 4: [3, 4]. Take 3, a leaf, then 4, a leaf, and the queue is empty. The output is 0, 1, 2, 3, 4. Grouped, level 0 is [0], level 1 is [1, 2] and level 2 is [3, 4], so the tree has 3 levels. In-order on the same tree gives 3, 1, 0, 2, 4, a quite different list.
The queue holds up to one full level at a time. In a complete tree the bottom level has about half of all the nodes, so a tree of a million nodes can have around half a million waiting in the queue at once.
Time: every node is queued once and taken out once, so the work is proportional to the N nodes. Space: the queue holds at most the widest level, which is O(N) in the worst case, and the output holds all N values.