Example #1
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);
  }