Basic Tree-search algorithm for searching a node (with value k) in a binary search tree.
‘x’ denotes the node of the binary search tree.
TREE-SEARCH (x, k)
if x= NIL or k = key[x]
then return x
if k < key[x]
then return TREE-SEARCH(left[x], k)
else return TREE-SEARCH(right[x], k)
Iterative Version:
ITERATIVE-TREE-SEARCH(x, k)
while x ≠ NIL and k ≠ key[x]
do if k < key[x]
then x ← left[x]
else x ← right[x]
return x
Shouldn’t the first line (of the iterative algorithm) actually be while (x ≠ NIL OR k ≠ key[x]) instead of (while x ≠ NIL and k ≠ key[x]) ?
By the way, if you were wondering, this is from one of the famous books of Algorithm Analysis.
No, it needs to be
andbecause otherwise you’ll dereference NIL ifkisn’t found. Remember thatwhileexecutes as long as the expression evaluates to true.If x is NIL, then the expression
x ≠ NIL and k ≠ key[x]is false, becausex ≠ NILis false. Either side of anandbeing false makes the whole expression false.If
orwere used instead,x ≠ NILwould still be false, but you’d need to evaluate the other side — both sides of anormust be false for theorto be false. Unfortunately, evaluating the other side dereferences NIL. Ooops. Even if it weren’t for that problem,k ≠ key[x]is true (because we’re considering the case where k isn’t found, so nokeyin the treexcan bek). Since one (or more) sides of theoris true, theorevaluates to true, and the loop continues forever.In English, that while can read: while there is still tree left (
x ≠ NIL) and we haven’t yet found what we’re looking for (k ≠ key[x]).