Proofs: Treap merge
These are the human proofs of Treap merge, at full length.
Treap merge returns a treap of the union full
This proof shows: correctness.
A treap is a binary tree with (P1) the search order on keys and (P2) the max-heap order on priorities. Write for the set of keys of the subtree , and for its set of nodes. In a treap, the root has the highest priority of all its nodes, since every node is reached from the root by edges that do not increase the priority.
Theorem. Let and be treaps or nil, with for every and . Then MERGE returns a treap with and , and its root is the root of or of . Each node keeps its key and priority.
Proof. By induction on . If is nil, line L1 returns , which is right; if is nil, line L2 returns .
Case (lines L3 to L5). The pair and meets the precondition: the keys of are keys of , so they are less than the keys of . It has one node fewer, so by induction line L4 makes a treap with keys , whose root is the old root of or the root of . We check that with left subtree and right subtree is a treap.
- (P1) at the root: the keys of are less than , as before. The keys of are keys of , which are greater than , or keys of , which are greater than every key of . Inside and , (P1) holds.
- (P2) at the root: the left child is unchanged. The root of is the root of , whose priority is at most by (P2) in , or the root of , whose priority is less than . Inside and , (P2) holds.
The keys are , the nodes likewise, and the root is the root of .
Case (lines L6 and L7). This is the mirror image. The pair and meets the precondition, so by induction line L6 makes a treap with keys whose root is the root of or of . Its keys are keys of , less than every key of and so less than , or keys of , less than . Its root has priority or at most by (P2) in . So with the left subtree and its old right subtree is a treap with the keys , and its root is the root of .
Termination and cost. Each call either stops or recurses with one node fewer in total, and the node that is set aside is the root of or of . In the first case the next call works on , a step down the right spine of ; in the second case on , a step down the left spine of . So the number of calls is at most the length of the right spine of plus the length of the left spine of , plus one, and each call does work.