Proofs: Postorder traversal
These are the human proofs of Postorder traversal, at full length.
The stack-based postorder traversal lists the tree in postorder full
This proof shows: correctness, termination.
Let be an ordered tree rooted at , with child lists , and let be the postorder of the subtree of : 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 on top, and out is . Then after exactly more steps, the stack is and out is . During these steps no pair of is read or changed.
Proof. By strong induction on the height of . Let .
Base, . The next step reads at line L4. The test of line L5 fails, so lines L9 and L10 pop the pair and append . One step was used, , and out is .
Step, . Each child has a smaller height, so the claim holds for it. By an inner induction on : after steps, the stack is and out is . This holds for . For , the next step reads , finds , changes the pair to and pushes at lines L6 and L7. It appends nothing. By the claim for , after more steps the stack is and out has grown by , and the pairs below were not touched. That is steps in all, which proves the inner step.
At the next step finds , pops and appends . So out is , and the stack is . The number of steps is , because the subtrees of the children partition the vertices of other than . Only the pair of and the pairs above it were read or changed.
Theorem. POSTORDER stops after steps and returns .
Proof. After lines L1 and L2, out is empty and the stack is the empty stack followed by . By the claim with empty, after steps the stack is empty and out is . The test of line L3 then fails, and line L11 returns out. The number of steps is finite, so the procedure terminates.
Stack size. By the claim, the pairs on the stack are always the vertices of one path that starts at and goes down. So the stack holds at most pairs, where is the height of .