Proofs: Binary search tree search
These are the human proofs of Binary search tree search, at full length.
BST search returns the node with the key, or NIL when there is none full
This proof shows: correctness, termination.
Let be a binary search tree with root , with the strict binary search tree property, and let be a key. For a node (or NIL) write for the set of nodes of the subtree rooted at , with . The keys of are distinct, so at most one node has .
Claim. TREE-SEARCH stops after at most runs of the loop, where is the height of . It returns if exists, and NIL else. It does not change .
Invariant (I). At the test of line L1: if exists, then . Also, is NIL or a node of depth , where is the number of runs of the loop done so far.
Initialization. Before the first test, , , and is the whole tree, so (I) holds.
Maintenance. Suppose (I) holds and NIL. If , line L2 returns and the loop ends. Else assume , so line L3 sets to . Each node in the right subtree of has by the BST property, and . So , if it exists, is in but is not and not in the right subtree; hence . The depth of is . The case (line L4) is the same with left and right swapped, using for each in the left subtree. So (I) holds after the step.
Termination. By (I), after runs is NIL or has depth . So after at most runs, is NIL, or the loop has returned. The quantity is a non-negative integer that drops by exactly 1 in each run.
The answer. If line L2 returns , then , so . If the loop ends with $x = $ NIL, line L5 returns NIL; by (I) if exists, so does not exist and NIL is right. The algorithm writes only the local variable , so does not change.
The cost. The proof also shows that the number of runs is , where is the depth of the last node visited, because each run visits one node at depth and the depths are .