next up previous contents
Next: Deletion revisited Up: Binary search trees Previous: Primitive operations on trees   Contents

Searching yet again

Using these primitive functions on trees, our searching algorithm can be now written as

  boolean isin(value v, tree t) {

  if (EmptyTree(t))
     return False;
  else
     if (v = Root(t))
        return true;
     else
        if (v < Root(t))
           return isin(v, Left(t));
        else
           return isin(v, Right(t));
  }

Recursive algorithms of this kind have a slight variant known as inductive definitions, which take the form of equations (for the base case and the inductive step). The inductive definition corresponding to the above recursive algorithm is the following:

isin(v,EmptyTree) = False
isin(v,MkTree(w,l,r)) = if (v = w)
                        then True
                        else if (v < w)
                             then isin(v,l)
                             else isin(v,r)
Here we have used a variant of the if-then-else control operator of the form
   if <boolean-expression> then <value> else <value>
rather than the more usual
   if <boolean-expression> then <command> else <command>
In C and Java, the form using expressions rather than commands have to be written in the following more obscure way:
   <boolean-expression> ? <value> : <value>
For example, the expression
    (2 == 4) ? 1 : 3
evaluates to 3.

Inductive definitions are usually easier to read than recursive algorithms. However, languages such as C and Java don't have mechanisms for writing down inductive definitions (the usual mechanism is known as pattern-matching) and hence we first have to transform them into recursive algorithms. But other languages, such as Prolog, ML and Haskell do allow such definitions. In fact, the inductive definition displayed above is almost literally a program in ML or Haskell.


next up previous contents
Next: Deletion revisited Up: Binary search trees Previous: Primitive operations on trees   Contents
Martin Escardo 2005-01-11