next up previous contents
Next: Primitive operations on trees Up: Binary search trees Previous: A Java implementation of   Contents

Searching again

Algorithms can be expressed in many ways. Here is a concise description of the search algorithm that we have already discussed.

In order to search for a value $ v$ in a binary search tree $ t$, proceed as follows. If $ t$ is empty then $ v$ doesn't occur in $ t$ and hence we stop. Otherwise, if $ v$ is equal to the root of $ t$ then $ v$ does occur in $ t$ and hence we again stop. If, on the other hand, $ v$ is smaller than the root, then, by definition of binary search tree, it is enough to search on the left subtree of $ t$. Hence replace $ t$ by its left subtree and carry on in the same way. The case in which $ v$ is bigger than the root is handled in a similar way.
Notice that such a description of an algorithm embodies both the steps that need to be carried out and the reason why this gives a correct solution to the problem. This way of describing algorithms is very common when we don't intend to run them in a computer. When we do, further refinement is necessary. A next step in the refinement could be:
boolean isin(value v, tree t) {
  if (t is empty)
     return False;
  else
     if (v is equal to the root node of t)
        return true;
     else
        if (v < root node of t)
           return isin(v, left subtree of t);
        else
           return isin(v, right subtree of t);
}
This is another example of a recursive algorithm. The recursion eventually terminates, because every recursive call takes a smaller tree, so that we eventually find what we are looking for or reach an empty tree. In this example, the recursion is easily transformed into a while-loop:
boolean isin(value v, tree t) {
  while (t is not empty  and  v is different from the root of t)
        if (v < root node of t)
           t = left subtree of t;
        else
           t = right subtree of t;

  if (t is empty)
     return false;
  else
     if (v is equal to the root of t)
        return true;
     else
        return false; 
}
Using boolean expressions, the part below the while-loop can be simplified to
  return ((t is not empty) and (v is equal to the root of t));
The idea is that each of the expressions is evaluated to a boolean value, then its logical conjunction (``and'') is taken, and finally the obtained truth value is returned.


next up previous contents
Next: Primitive operations on trees Up: Binary search trees Previous: A Java implementation of   Contents
Martin Escardo 2005-01-11