Beispiel #1
0
  /**
   * Internal method to find an item in a subtree.
   *
   * @param x is item to search for.
   * @param t the node that roots the tree.
   * @return node containing the matched item.
   */
  private AvlNode find(Comparable x, AvlNode t) {
    while (t != null)
      if (x.compareTo(t.element) < 0) t = t.left;
      else if (x.compareTo(t.element) > 0) t = t.right;
      else return t; // Match

    return null; // No match
  }
Beispiel #2
0
 /**
  * Internal method to insert into a subtree.
  *
  * @param x the item to insert.
  * @param t the node that roots the tree.
  * @return the new root.
  */
 private AvlNode insert(Comparable x, AvlNode t) {
   if (t == null) t = new AvlNode(x, null, null);
   else if (x.compareTo(t.element) < 0) {
     t.left = insert(x, t.left);
     if (height(t.left) - height(t.right) == 2)
       if (x.compareTo(t.left.element) < 0) t = rotateWithLeftChild(t);
       else t = doubleWithLeftChild(t);
   } else if (x.compareTo(t.element) > 0) {
     t.right = insert(x, t.right);
     if (height(t.right) - height(t.left) == 2)
       if (x.compareTo(t.right.element) > 0) t = rotateWithRightChild(t);
       else t = doubleWithRightChild(t);
   } else ; // Duplicate; do nothing
   t.height = max(height(t.left), height(t.right)) + 1;
   return t;
 }