Proofs: Preorder traversal
These are the human proofs of Preorder traversal, at full length.
The stack-based preorder traversal lists the tree in preorder full
This proof shows: correctness, termination.
Let be an ordered tree rooted at , with child lists . Write for the preorder of the subtree of , and for the same sequence without its first entry . So for . One step is one run of the body of the loop (lines L4 to L10).
Claim. Suppose that at some moment the stack is followed by the pair on top, the last entry of out is , and out is at this moment. Then after exactly more steps, the stack is , out is , and during these steps no pair of is read or changed.
Proof. By strong induction on the height of . Let .
If , is a leaf, has one vertex, and is empty. In the next step, line L4 reads , the test of line L5 fails, and line L10 pops . That is step, and out is still .
If , each child has a smaller height than , so the claim holds for it. We show by induction on : after steps, the stack is and out is . For this is the start. For , the next step reads , finds at line L5, sets the pair to , appends to out and pushes . Now the hypothesis of the claim holds for , so after more steps the stack is again and out has grown by . The steps used are , and the claim for says that the pairs below it, including and , are not touched.
At , the stack is and out is . The next step finds at line L5 and pops . The total number of steps is , because the subtrees of the children partition minus . Only the pair of and pairs above it were read or changed.
Theorem. PREORDER stops after steps and returns , where is the number of vertices.
Proof. After lines L1 and L2, the stack is the empty stack followed by , and out is . The claim applies with . After steps the stack is empty, so the test of line L3 fails, and out is . Line L11 returns it. The count of steps is finite and exact, so the loop terminates.
Stack size. By the claim, while the walk is inside , the pair of stays on the stack, and the pairs on the stack at any moment are the vertices of one path from down. So the stack never holds more than pairs, where is the height of .