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.