Proofs: Binary search tree insertion
These are the human proofs of Binary search tree insertion, at full length.
BST insertion keeps the BST property and adds exactly the new key full
This proof shows: correctness, termination.
Let be a binary search tree with the strict binary search tree property, correct parent pointers, nodes and key set . Let be a key and a value. For a node write for the nodes of its subtree.
Claim. TREE-INSERT stops after at most runs of the loop, where is the height of . Afterwards: (a) if , the tree has the same nodes and links, and the node with key has value ; (b) if , the tree has the nodes of plus one new leaf with key and value , it has the BST property, its parent pointers are correct, and . No other value changes.
Step 1: the loop is the search. Lines L2 to L6 make the same moves as BST search for : at each node they stop on equality and else go to the left child if and to the right child if . Line L3 only copies to before the move. By the correctness of BST search, if the loop reaches the node with key , and line L6 sets its value and returns; no link changes, which proves (a). The depth of grows by 1 in each run, so the loop runs at most times.
Step 2: the end of the path. Now let . Let be the nodes that takes in the loop, with ( when is empty). The loop ends when $x = $ NIL, so , and the move out of was to the left child if and to the right child else, and that child is NIL. For each , is the left child of if and the right child if .
Step 3: the new leaf. If is empty, line L8 makes the root, with no parent, and a tree with one node has the BST property. Else lines L9 and L10 make the child of on the side given by the comparison of with , which is the NIL child of Step 2, so no subtree is lost. Line L7 sets .
Step 4: the BST property. Take a node of the new tree and a node in its left subtree; we show (the right side is the mirror image).
- If , then has no subtrees, so there is no .
- If and , then was in the left subtree of in , because the insert adds a leaf and changes no other link. So by the property of .
- If , then is an ancestor of , so for some , and is in the left subtree of exactly when the path went left at , that is when . So .
Step 5: links and count. The only new links are (or the root field) and , and they agree. has no children. Line L11 adds 1 to . The keys of the new tree are , and each old node keeps its key and value. This proves (b).
Corollary (sequence of inserts). By induction on the number of inserts, a tree built from the empty tree by TREE-INSERT has the BST property, and its in-order sequence is the sorted list of the distinct keys inserted, each with the value of its last insert.