views:

432

answers:

1

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.

+1  A: 

No, it needs to be and because otherwise you'll dereference NIL if k isn't found. Remember that while executes as long as the expression evaluates to true.

while x ≠ NIL and k ≠ key[x]

If x is NIL, then the expression x ≠ NIL and k ≠ key[x] is false, because x ≠ NIL is false. Either side of an and being false makes the whole expression false.

If or were used instead, x ≠ NIL would still be false, but you'd need to evaluate the other side — both sides of an or must be false for the or to 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 no key in the tree x can be k). Since one (or more) sides of the or is true, the or evaluates 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]).

derobert
Isn't the OR part what is actually desired?I mean if you come to the part where x= NIL, just come out and return x, OR if you did find the key, again just return and print x.Rather than wait for both to occur at once. Is my understanding correct?
halluc1nati0n
EDIT: Oh, I'm getting it now, the while loop always has a parameter with a kinda tricky logic :DIf we go to x=NIL and have the OR keyword, the k ≠ key[x] would still hold, and thus, the while loop would still try to execute(which we don't intend).It's funny, I kinda think it was dumb of me to even ask this as a question now!
halluc1nati0n