基础概念
AVL树是一颗空树或者左右两个子树的高度差的绝对值不超过1,且左右两颗子树都是平衡二叉树。
结点深度:
//返回以该结点为根结点的树高度
public int height() {
return Math.max((left == null) ? 0 : left.height(), (right == null) ? 0 : right.height()) + 1;
}
左旋转:
private void leftRotate() {
//创建新的结点,value为根结点的值;this即为根节点
Node newNode = new Node(value);
newNode.left = this.left;
newNode.right = this.right.left;
this.value = this.right.value;
this.left = newNode;
this.right = this.right.right;
}
右旋转
private void rightRotate() {
//创建新的结点,value为根结点的值;this即为根节点
Node newNode = new Node(value);
newNode.right = this.right;
newNode.left = this.left.right;
this.value = this.left.value;
this.right = newNode;
this.left = this.left.left;
}
双向旋转:
如果是以下情况,左旋、右旋后仍是非平衡二叉树;需要先对左子树or右子树进行旋转
//添加结点
public void add(Node node) {
if (node == null)
return;
if (this.value > node.value) {
if (this.left == null)
this.left = node;
else
this.left.add(node);
} else {
if (this.right == null)
this.right = node;
else
this.right.add(node);
}
if (rightHeight() - leftHeight() > 1) {
if (right != null && right.leftHeight() > right.rightHeight())
right.rightRotate();
leftRotate();//左旋转
}
if (leftHeight() - rightHeight() > 1) {
if (left != null && left.rightHeight() > left.leftHeight())
left.leftRotate();//先对当前结点的左子树进行左旋转
rightRotate();//右旋转
}
}