Proofs: Left-child right-sibling representation
These are the human proofs of Left-child right-sibling representation, at full length.
The left-child right-sibling operations keep the chain invariant and traverse in preorder full
This proof shows: correctness.
We use the pseudocode of the page. The invariant is:
(S1) For each node with children from left to right: if then $p.child = $ NIL; if then , for , and $c_k.sibling = $ NIL. (S2) for each child of , and the root has no parent and no sibling.
A tree with one node, the root, meets (S1) and (S2) with all links NIL.
ADD-CHILD. Let have the children , and let be a new node with no children, so $x.child = $ NIL. After the call, has the children . Line L3 sets . Line L2 sets to the old , which by (S1) is if and NIL if . The links do not change. So (S1) holds for . Line L1 sets , so (S2) holds for . No other node changes, and has no children, so (S1) and (S2) hold for each node.
CHILDREN. By (S1), the sequence is and then NIL. Lines L4 to L7 report exactly this sequence and stop after steps of line L7.
PREORDER. Write for the preorder of the subtree of : , then for the children of . For a node with right siblings (that is, and $y_j.sibling = $ NIL), write , the concatenation. By (S1), when NIL, and otherwise.
Define the pending sequence of a stack , with on top, as , where for the start node and for each other node. We claim that before each test of line L9,
(P) the nodes reported so far, followed by the pending sequence of , is .
Initialization. Line L8 makes and nothing is reported. The pending sequence is .
Maintenance. Let be the top of . Line L10 pops it and line L11 reports it.
- If , then , or just if has no child. Line L12 pushes nothing. Line L13 pushes if it exists, with .
- If , then , with the second factor empty if $x.sibling = $ NIL. And , with the second factor empty if $x.child = $ NIL. Line L12 pushes if it exists, and then line L13 pushes on top of it if it exists.
In each case, the reported followed by the pending sequence of the pushed nodes, top first, is . The rest of the stack is unchanged. So (P) holds again.
Termination. Each iteration reports one node, and by (P) the reported nodes are a prefix of , which has nodes, so there are at most iterations. The loop stops when is empty, and then the pending sequence is empty, so by (P) the reported sequence is .
The same argument, with and a mark on each node whose children were pushed, proves the postorder routine of the implementation.
Binary-tree view. Let be the binary tree on the same nodes with and . Then is the preorder of the subtree of in : by induction on the size of this subtree, its preorder is , then the preorder of the subtree of , then that of , which is by the equation above. For the root, which has no sibling, this gives that the preorder of the tree is the preorder of .
Cost. Each line of ADD-CHILD is . CHILDREN does work for each of the children, plus . PREORDER does work in each of its at most iterations.