Пример #1
0
  /** x y / \ / \ A y => x C / \ / \ B C A B */
  private void leftRotate(Node<T> x) {
    Node<T> parent = x.parent;

    Node<T> y = x.right;
    Node<T> B = y.left;
    y.left = x;
    x.parent = y;
    x.right = B;
    if (B != null) B.parent = x;

    y.parent = parent;
    if (parent != null) {
      parent.replaceChild(x, y);
    } else {
      root = y;
    }

    updateHeight(x);
  }
Пример #2
0
  /** x x x x \ \ / / y y y y \ / / \ z z z z */
  private void balance(Node<T> x, Node<T> y) {

    if (!x.isBalanced()) {
      if (x.right != null && x.right == y) {
        if (y.isRightHeavy()) {
          leftRotate(x);
        } else if (y.isLeftHeavy()) {
          rightRotate(y);
          leftRotate(x);
        }
      }

      if (x.left != null & x.left == y) {
        if (y.isLeftHeavy()) {
          rightRotate(x);
        } else if (y.isRightHeavy()) {
          leftRotate(y);
          rightRotate(x);
        }
      }
    }

    if (x.parent != null) balance(x.parent, x);
  }
Пример #3
0
 private void addToRight(Node<T> parent, Node<T> newNode) {
   countNodes++;
   parent.right = newNode;
   newNode.parent = parent;
 }
Пример #4
0
 private void updateHeight(Node<T> node) {
   while (node != null) {
     node.updateHeight();
     node = node.parent;
   }
 }
Пример #5
0
 private void addToLeft(Node<T> parent, Node<T> newNode) {
   countNodes++;
   parent.left = newNode;
   newNode.parent = parent;
 }