Пример #1
0
  public static void rotateRight(AVLNode origRoot) {

    // === Difference from rotateLeft ===
    AVLNode newRoot = origRoot.left;
    // Original root's left (previously new root) becomes new root's right
    origRoot.left = newRoot.right;
    // New root's right becomes original root
    newRoot.right = origRoot;

    // If original root is not root of tree
    if (origRoot.parent != null) {
      // Update new root's parent's link to it based on
      // whether original root is left or right child
      if (origRoot.parent.left.key == origRoot.key) {
        origRoot.parent.left = newRoot;
      } else {
        origRoot.parent.right = newRoot;
      }
    }
    // Update new root's parent to be original root's parent
    newRoot.parent = origRoot.parent;
    // Update original root's parent to be new root
    origRoot.parent = newRoot;

    // Update heights of original and new root
    newRoot.height -= 1;
    origRoot.height += 1;
  }
Пример #2
0
  /**
   * Perform a right (clockwise) rotation at <tt>x</tt>.
   *
   * @param x the lowest unbalanced node found in this tree.
   * @return The new root of the balanced subtree.
   */
  private AVLNode<E> rightRotation(AVLNode<E> x) {
    AVLNode<E> newRoot = (AVLNode<E>) x.leftChild;
    newRoot.parent = x.parent;
    x.parent = newRoot;
    x.leftChild = newRoot.rightChild;
    // newRoot is guaranteed to have a left child, but
    //  we can't be sure it has a right child
    if (newRoot.rightChild != null) {
      newRoot.rightChild.parent = x;
    }
    newRoot.rightChild = x;

    // lastly: do updates from the bottom up
    updateBalanceAndHeight(x);
    updateBalanceAndHeight(newRoot);
    return newRoot;
  }