previous | start | next

Key floor(key) - final version

public class BST<Key extends Comparable<Key>, Value>
{

  public Key floor(Key k)
  {
   
    return floor(k, null, root);
  }

  /**
   * returns the floor of k
   * @param k the search key
   * @param candidate largest key in the tree but not in subtree t 
   * that is less than k (might be null)
   * @param t subtree that contains the floor of k or that is empty if
   * the floor of k is candidate
   *
   * @return the floor of k in the subtree t or candidate if 
   * k is larger than all keys in subtree t.
   */
  private Key floor(Key k, Key candidate, Node t)
  {

    if (t == null) return candidate;
    int cmp = k.compareTo(t.key);
    if (cmp < 0) {
      return floor(k, candidate, t.left);
    } else if (cmp > 0) {
      return floor(k, t.key, t.right);
    } else {
      return t.key;
    }
  }

}


previous | start | next