previous | start | next

Java Details for Using Recursion

These recursive methods generaly need to have a Node as a parameter!

Consequently, these methods can't be public.

So the pattern that arises is to have one public method that doesn't require a Node parameter and to have a private recursive method that is called to do all the work.

For example, here is a pair of get methods, one public and one private:

public Value get(Key k)
{
  // Call the private recursive find 
  // starting at the root of the tree.
  return get( k, root);
}

private Value get(Key k, Node t)
{
  if ( t == null ) {  // Base case
      return null;
  }
  if ( k.compareTo(t.key) < 0 ) { // reduce search to left subtree
      return get(k, t.left);
  }
  else if ( k.compareTo(t.key) > 0 ) { // or to the right subtree
      return get(k, t.right);
  }
  else  {
      return t.val;  // or Node with the key is found; return its value!
  }
}


previous | start | next