Proofs: Leftist heap
These are the human proofs of Leftist heap, at full length.
Merge keeps a leftist heap, and the right spine is short full
This proof shows: correctness.
A leftist heap is a binary tree with the invariant (L1) heap order, (L2) at each node, and (L3) at each node, with . Write for the multiset of keys of a tree .
Lemma 1. A leftist tree whose root has rank has at least nodes, so .
Proof. We show first that every path from the root down to an empty subtree has at least nodes, by induction on the number of nodes. An empty tree has . For a node of rank , a path goes to the left or to the right subtree. The right subtree has rank by (L3), and the left subtree has rank at least by (L2). By induction, the path has at least nodes below , so at least with . So all nodes at depths to exist, which gives at least nodes. Then , so .
Lemma 2. If and are the roots of leftist heaps and , possibly empty, then returns the root of a leftist heap with , and it makes at most calls.
Proof. By induction on . If or is NIL, line L1 returns the other heap with one call, and the claim holds. Otherwise, after line L2, . The call at line L3 has the arguments and , and by (L3). By induction, it returns a leftist heap with the keys of the right subtree of and of , after at most calls. So the total number of calls is at most .
Now check the invariant at the node after lines L3 to L5. All other nodes are in the left subtree of , which did not change, or in , which is a leftist heap.
- (L1) Every key of is a key of the old right subtree of , which is at least by heap order of , or a key of , which is at least by heap order of . The left subtree of did not change. So heap order holds at , and a swap of the children does not change this.
- (L2) After line L4, the child of the larger rank is on the left.
- (L3) Line L5 sets from the final right child.
The keys of are the keys of , its left subtree and , which is .
Theorem. INSERT, DELETE-MIN and MELD keep the invariant, and DELETE-MIN returns a smallest key. Each of them takes time.
Proof. A new node with rank 1 and no children is a leftist heap. By Lemma 2, line L7 returns a leftist heap with the old keys and . In DELETE-MIN, the root holds a smallest key, because by heap order every key is at least the key of its parent, and so, by induction on the depth, at least the key of the root. The two subtrees of the root are leftist heaps, because the invariant is local to each node. By Lemma 2, line L8 returns a leftist heap with all keys except the key of the root. Meld is a single MERGE.
By Lemma 2 and Lemma 1, MERGE makes at most calls, each with work outside the recursion. So each operation takes time.