Iterative version of binary tree search

The basic tree search algorithm for finding a node (with a value of k) in a binary search tree. 'x' stands for 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

Should the first line (of the iterative algorithm) be in time (x β‰  NIL OR k β‰  key [x]) instead of (while x β‰  NIL and k β‰  key [x])?

By the way, if you're interested, this is from one of the well-known books of algorithm analysis.
+3
source share
1 answer

No, it should be and, because otherwise you will look for NIL if knot found. Remember that it whileis executed until the expression evaluates to true.

while x β‰  NIL and k β‰  key[x]

x NIL, x β‰  NIL and k β‰  key[x] , x β‰  NIL . and, false, .

or, x β‰  NIL , - or or . , NIL. . , k β‰  key[x] ( , k , no key x k). ( ) or , or true, .

: (x β‰  NIL) , , (k β‰  key[x]).

+2

Source: https://habr.com/ru/post/1718980/


All Articles