Beispiel #1
0
 private AvlNode<T> rotateWithRightChild(AvlNode<T> k2) {
   AvlNode<T> k1 = k2.right;
   k2.right = k1.left;
   k1.left = k2;
   k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
   k1.height = Math.max(k2.height, height(k1.right)) + 1;
   return k1;
 }
Beispiel #2
0
 /**
  * Rotate binary tree node with right child. For AVL trees, this is a single rotation for case 4.
  * Update heights, then return new root.
  */
 private static AvlNode rotateWithRightChild(AvlNode k1) {
   AvlNode k2 = k1.right;
   k1.right = k2.left;
   k2.left = k1;
   k1.height = max(height(k1.left), height(k1.right)) + 1;
   k2.height = max(height(k2.right), k1.height) + 1;
   return k2;
 }
Beispiel #3
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;
 }
Beispiel #4
0
 public AvlNode<T> insert(T x, AvlNode<T> t) {
   if (t == null) return new AvlNode<>(x, null, null);
   int compareResult = compare(x, t.element);
   if (compareResult < 0) {
     t.left = insert(x, t.left);
     if (height(t.left) - height(t.right) == 2)
       if (compare(x, t.left.element) < 0) t = rotateWithLeftChild(t);
       else t = doubleWithLeftChild(t);
   } else if (compareResult > 0) {
     t.right = insert(x, t.right);
     if (height(t.right) - height(t.left) == 2)
       if (compare(x, t.right.element) > 0) t = rotateWithRightChild(t);
       else t = doubleWithRightChild(t);
   } else ;
   t.height = Math.max(height(t.left), height(t.right)) + 1;
   return t;
 }