Proofs: Balanced parentheses representation
These are the human proofs of Balanced parentheses representation, at full length.
Correctness of navigation on the BP representation full
This proof shows: correctness.
Let be written by a preorder traversal, ( on entering a node and ) on leaving it, let and be the positions of the two parentheses of , and let be the excess of , with .
Lemma 1 (nesting). consists of the parentheses of the descendants of , and of nothing else. The traversal enters , then visits the subtrees of its children one after another, then leaves . By induction on the height of , each child's subtree writes exactly its own pairs, and nothing else is written between and .
Lemma 2 (excess). and , with the root at depth 0. The nodes entered and not yet left right after are and its ancestors, each with one unmatched ( and no other open pair; after , is closed too. Lemma 1 also shows that for : inside the subtree, itself stays open. So , the first position after with excess .
FIRST-CHILD. If has children, its first child is entered right after , so is its opening. If not, is left right away and .
NEXT-SIBLING. After leaving at , the traversal enters the next child of the parent if one exists, writing ( at ; otherwise it leaves the parent, writing ). The root has no next position.
PARENT. By Lemma 2 only the root has . Otherwise let be the parent. By Lemma 1, the pair of contains the pair of , and so do the pairs of all ancestors of , and no other pair does. The tightest of them is the deepest ancestor, , which is .
SUBTREE-SIZE. By Lemma 1 the range holds two parentheses for each node of the subtree, so its length is twice the size.
DEPTH. Lemma 2.
IS-ANCESTOR. is an ancestor of or exactly when the pair of lies in the pair of , by Lemma 1, that is, when ; the pair of a non-descendant either ends before or starts after .
LCA. Let , with not an ancestor of , and let be their lowest common ancestor. Then lies in the subtree of a child of and in the subtree of a later child , , since is the lowest common ancestor and is not an ancestor of . Let . On :
- every position inside the pair of a child of has excess at least , by Lemma 2 applied to that child, since its own
(is still open; - the positions lie in the range, because (Lemma 1) and , and each has excess exactly ;
- the range lies inside the pair of and after , and is followed directly by , so every position of the range is either inside the pair of some child or is one of the closings .
So the minimum of on is , reached first at , or at another with . In every case is the opening of , a child of , and by the PARENT case. If is an ancestor of , the answer is , which line L12 returns.