示例#1
0
 private AVLNode SingleRotateWithRight(AVLNode k2) {
   AVLNode k1;
   k1 = k2.getRight();
   k2.setRight(k1.getLeft());
   k1.setLeft(k2);
   k2.setHeight(Math.max(Height(k2.getLeft()), Height(k2.getRight())) + 1);
   k1.setHeight(Math.max(Height(k1.getLeft()), k2.getHeight()) + 1);
   return k1;
 }
示例#2
0
  /**
   * 1.如果是null节点,则直接返回null 2.如果删除的值<当前节点,则转入left节点进行递归删除 3.如果删除的值>当前节点,则转入right节点进行递归删除
   * 4.如果删除的值为当前节点,如果当前节点只有一个子树,则直接返回该子树 5.如果删除的值为当前节点,且当前节点有两个子树,则将当前值更改为右子树中最小的节点值,并递归在右子树中删除该节点值
   * 6.重新修正该处理节点的height值 7.对处理节点进行重新翻转处理,以修正在删除过程中可能出现的树不平衡情况
   *
   * @param x
   * @param T
   * @return
   */
  private AVLNode remove(int x, AVLNode T) {

    if (T == null) return null;
    if (x < T.getValue()) {
      T.setLeft(remove(x, T.getLeft()));

    } else if (x > T.getValue()) {
      T.setRight(remove(x, T.getRight()));

    } else if (T.left != null && T.right != null) {
      T.setValue(findMin(T.getRight()).getValue());
      T.setRight(remove(T.getValue(), T.getRight()));
    } else {
      T = T.getLeft() == null ? T.getRight() : T.getLeft();
    }

    if (T != null) T.setHeight(Math.max(Height(T.getLeft()), Height(T.getRight())) + 1);

    T = rotate(T);
    return T;
  }
示例#3
0
  AVLNode insert(int x, AVLNode T) {
    if (T == null) {
      T = new AVLNode();
      T.setValue(x);
      T.setLeft(null);
      T.setRight(null);
    } else if (x < T.getValue()) {
      T.setLeft(insert(x, T.getLeft()));
      if (Height(T.getLeft()) - Height(T.getRight()) == 2) {
        if (x < T.getLeft().getValue()) T = SingleRotateWithLeft(T);
        else T = DoubleRotateWithLeft(T);
      }
    } else if (x > T.getValue()) {
      T.setRight(insert(x, T.getRight()));
      if (Height(T.getRight()) - Height(T.getLeft()) == 2)
        if (x > T.getRight().getValue()) T = SingleRotateWithRight(T);
        else T = DoubleRotateWithRight(T);
    }

    T.setHeight(Math.max(Height(T.getLeft()), Height(T.getRight())) + 1);
    return T;
  }