Proofs: Level-order traversal
These are the human proofs of Level-order traversal, at full length.
The queue-based traversal visits a binary tree in level order full
This proof shows: correctness, termination.
Let be a binary tree with nodes; for the empty tree, line L1 returns and the empty list is correct. Let be the list of the nodes of depth sorted by the relation "left of", for , where is the height. The level order is the concatenation .
Lemma 1 (left of, one level down). Let be nodes of depth with parents and . If , then is left of if and only if is left of . If , then is left of if and only if is the left child and is the right child.
Proof. If , the deepest common ancestor of and is , and the claim is the definition. If , then and have the same depth , and neither is an ancestor of the other. A common ancestor of and is not or , so it is a common ancestor of and , and conversely. So the deepest common ancestor is the same, and the paths from to and to start with the same child of , and so do those to and to . So the two relations agree.
Lemma 2. Write for the list of the children of , the left child first. If , then .
Proof. Each node of depth has exactly one parent, of depth , so the right side lists each node of depth exactly once. Two nodes in the same block are in the right order by the second part of Lemma 1, and two nodes in blocks and with are in the right order by the first part, because is left of .
FIFO order. Let be the sequence of the nodes in the order in which they are enqueued. A FIFO queue dequeues in the order of enqueuing, so the nodes are visited in the order , as far as the loop runs. By lines L2, L6 and L7, starts with the root, and for each visited node , the block is appended to at the visit of . So , where are the entries of in order.
Claim. .
Proof. We show by induction on that starts with . For , starts with the root, and is the root. Assume that starts with . The entries of contribute, by the FIFO order, the blocks of their children, which are by Lemma 2, and these come right after the root. So the children of the entries of are appended next, in the order of , and by Lemma 2 they form . So starts with . Each node is in exactly one and is enqueued only by its parent or at line L2, so has no other entries.
Termination. Each node is enqueued at most once, by its unique parent or, for the root, at line L2, so there are enqueues, and the loop of line L3 runs times.
Theorem. LEVEL-ORDER visits each node of exactly once, in the level order .
Proof. The loop ends after iterations, when every enqueued node is dequeued. The visits follow the order , which is the level order by the claim.