Algorithm Search⌘K

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 TT be a binary search tree with root rr, with the strict binary search tree property, and let kk be a key. For a node xx (or NIL) write sub(x)\mathrm{sub}(x) for the set of nodes of the subtree rooted at xx, with sub(NIL)=∅\mathrm{sub}(\mathrm{NIL}) = \emptyset. The keys of TT are distinct, so at most one node tt has t.key=kt.key = k.

Claim. TREE-SEARCH(r,k)(r, k) stops after at most h+1h + 1 runs of the loop, where hh is the height of TT. It returns tt if tt exists, and NIL else. It does not change TT.

Invariant (I). At the test of line L1: if tt exists, then t∈sub(x)t \in \mathrm{sub}(x). Also, xx is NIL or a node of depth jj, where jj is the number of runs of the loop done so far.

Initialization. Before the first test, x=rx = r, j=0j = 0, and sub(r)\mathrm{sub}(r) is the whole tree, so (I) holds.

Maintenance. Suppose (I) holds and x≠x \ne NIL. If k=x.keyk = x.key, line L2 returns and the loop ends. Else assume k<x.keyk < x.key, so line L3 sets xx to x′=x.leftx' = x.left. Each node yy in the right subtree of xx has y.key>x.key>ky.key > x.key > k by the BST property, and x.key≠kx.key \ne k. So tt, if it exists, is in sub(x)\mathrm{sub}(x) but is not xx and not in the right subtree; hence t∈sub(x′)t \in \mathrm{sub}(x'). The depth of x′x' is j+1j + 1. The case k>x.keyk > x.key (line L4) is the same with left and right swapped, using y.key<x.key<ky.key < x.key < k for each yy in the left subtree. So (I) holds after the step.

Termination. By (I), after jj runs xx is NIL or has depth j≤hj \le h. So after at most h+1h + 1 runs, xx is NIL, or the loop has returned. The quantity h+1−jh + 1 - j is a non-negative integer that drops by exactly 1 in each run.

The answer. If line L2 returns xx, then x.key=kx.key = k, so x=tx = t. If the loop ends with $x = $ NIL, line L5 returns NIL; by (I) t∈sub(NIL)=∅t \in \mathrm{sub}(\mathrm{NIL}) = \emptyset if tt exists, so tt does not exist and NIL is right. The algorithm writes only the local variable xx, so TT does not change. ■\blacksquare

The cost. The proof also shows that the number of runs is d+1d + 1, where dd is the depth of the last node visited, because each run visits one node at depth jj and the depths are 0,1,…,d0, 1, \ldots, d.

Back to Binary search tree search