Proofs: Inorder traversal
These are the human proofs of Inorder traversal, at full length.
The stack-based inorder traversal lists each node once, in inorder full
This proof shows: correctness, termination.
Let the binary tree have the nodes and the root , or be empty with . For a node let be the set of nodes in the subtree of , with , and let be the inorder list of : and . Because the subtrees and are disjoint and do not contain , lists each node of exactly once.
Consider the state of INORDER at each test of line L2 and at each test of line L3. Write the stack as from bottom to top, and define
Lemma 1 (invariant). At every test of lines L2 and L3, .
Proof. By induction on the number of executed lines. Before the first test of line L2, line L1 has set , empty and , so .
Line L4 runs when . Before it, for the rest . It pushes and sets , so afterwards , which is by the definition of . So and do not change.
Lines L5 to L7 run when the test of line L3 fails, so and . The stack is not empty: the test of line L2 passed with or, if it passed with , line L4 ran at least once. So , where is the part for . Line L5 pops , line L6 appends it to , and line L7 sets . Afterwards has gained at its end and , so is unchanged.
Lemma 2 (each node is pushed at most once). Every node of appears in it exactly once, and a node is pushed only when it is the root of the first part of .
Proof. lists each node once, so each node is in exactly one of and . Line L4 pushes , which is in . After the push, is a stack entry and stays in until line L5 pops it and line L6 moves it to . After that, it is in for good: no line removes entries from . A node in is not in , so it is never again the value of at line L4: the values of at line L4 are roots of subtrees whose nodes are all in . So each node is pushed at most once.
Termination. Each pass of the inner loop pushes a node, so by Lemma 2 there are at most passes in all. Each pass of the outer loop pops a node, and a node can be popped only after it was pushed, so there are at most passes of the outer loop. So INORDER terminates, after at most pushes and pops.
Correctness. When the outer loop stops, and is empty, so , and by Lemma 1, . Since has exactly entries, there were exactly pushes and pops, and line L8 returns the inorder list of the tree.
Search trees. If the tree is a binary search tree with distinct keys, then for every node the keys of are smaller than and those of are larger. By induction on the height, the keys of are increasing: the keys of are increasing and below , and those of are increasing and above it. So the output lists the keys in sorted order.