一、AVL树概念
1.性质:首先是一棵二叉查找树(中序遍历有序),其次它是一棵空树或它的左右两棵子树的高度差的绝对值不超过1,并且左右两棵子树也是AVL树。
2.平衡因子
某节点的左子树和右子树的高度差即为该节点的平衡因子(BF,Balance Factor)。
二、AVL树基础设计
/**
* AVLTree是BST,所以节点值必须是可比较的
*/
public class AvlTree<E extends Comparable<E>>{
private class Node{
public E e;
public Node left;
public Node right;
public int height;
public Node(E e){
this.e = e;
this.left = null;
this.right = null;
this.height = 1;
}
}
private Node root;
private int size;
public AvlTree(){
root=null;
size=0;
}
//获取某一结点的高度
private int getHeight(Node node){
if(node==null){
return 0;
}
return node.height;
}
public int getSize(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
/**
* 获取节点的平衡因子
* @param node
* @return
*/
private int getBalanceFactor(Node node){
if(node==null){
return 0;
}
return getHeight(node.left)-getHeight(node.right);
}
//判断树是否为平衡二叉树
public boolean isBalanced(){
return isBalanced(root);
}
private boolean isBalanced(Node node){
if(node==null){
return true;
}
int balanceFactory = Math.abs(getBalanceFactor(node));
if(balanceFactory>1){
return false;
}
return isBalanced(node.left)&&isBalanced(node.right);
}
}
三、添加节点导致失衡的四种情况
1.LL型
LL:向左子树插入左孩子(left-left)导致不平衡
将LL情况抽象出来:
对节点y进行右旋操作:
右旋算法实现:
/**
* 右旋转
*/
private Node rightRotate(Node y){
Node x = y.left;
Node t3 = x.right;
x.right = y;
y.left = t3;
//更新height
y.height = Math.max(getHeight(y.left),getHeight(y.right))+1;
x.height = Math.max(getHeight(x.left),getHeight(x.right))+1;
return x;
}
2.RR型
RR:向右子树插入右孩子(right-right)导致的不平衡
将RR情况抽象出来:
对节点y进行左旋操作:
左旋算法实现:
/**
* 左旋转
*/
private Node leftRotate(Node y){
Node x = y.right;
Node t3 = x.left;
x.left = y;
y.right = t3;
//更新height
y.height = Math.max(getHeight(y.left),getHeight(y.right))+1;
x.height = Math.max(getHeight(x.left),getHeight(x.right))+1;
return x;
}
3.LR型
LR:向左子树插入右孩子导致的不平衡
将LR情况抽象出来:
旋转操作维持平衡:
4.RL型
RL:向右子树插入左孩子导致的不平衡
将RL情况抽象出来:
旋转维持平衡:
四、新增节点算法实现
// 向二分搜索树中添加新的元素(key, value)
public void add(E e){
root = add(root, e);
}
// 向以node为根的二叉查找树中插入元素(key, value),递归算法
// 返回插入新节点后二叉查找树的根
private Node add(Node node, E e){
if(node == null){
size ++;
return new Node(e);
}
if(e.compareTo(node.e) < 0)
node.left = add(node.left, e);
else if(e.compareTo(node.e) > 0)
node.right = add(node.right, e);
//更新height
node.height = 1+Math.max(getHeight(node.left),getHeight(node.right));
//计算平衡因子
int balanceFactor = getBalanceFactor(node);
if(balanceFactor > 1 && getBalanceFactor(node.left)>0) {
//右旋LL
return rightRotate(node);
}
if(balanceFactor < -1 && getBalanceFactor(node.right)<0) {
//左旋RR
return leftRotate(node);
}
//LR
if(balanceFactor > 1 && getBalanceFactor(node.left) < 0){
node.left = leftRotate(node.left);
return rightRotate(node);
}
//RL
if(balanceFactor < -1 && getBalanceFactor(node.right) > 0){
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
}
五、删除节点算法实现
public E remove(E e){
Node node = getNode(root, e);
if(node != null){
root = remove(root, e);
return node.e;
}
return null;
}
private Node remove(Node node, E e){
if( node == null )
return null;
Node retNode;
if( e.compareTo(node.e) < 0 ){
node.left = remove(node.left , e);
retNode = node;
}
else if(e.compareTo(node.e) > 0 ){
node.right = remove(node.right, e);
retNode = node;
}
else{ // e.compareTo(node.e) == 0
// 待删除节点左子树为空的情况
if(node.left == null){
Node rightNode = node.right;
node.right = null;
size --;
retNode = rightNode;
}
// 待删除节点右子树为空的情况
else if(node.right == null){
Node leftNode = node.left;
node.left = null;
size --;
retNode = leftNode;
}else {
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = remove(node.right, successor.e);
successor.left = node.left;
node.left = node.right = null;
retNode = successor;
}
}
if(retNode==null)
return null;
//维护平衡
//更新height
retNode.height = 1+Math.max(getHeight(retNode.left),getHeight(retNode.right));
//计算平衡因子
int balanceFactor = getBalanceFactor(retNode);
if(balanceFactor > 1 && getBalanceFactor(retNode.left)>=0) {
//右旋LL
return rightRotate(retNode);
}
if(balanceFactor < -1 && getBalanceFactor(retNode.right)<=0) {
//左旋RR
return leftRotate(retNode);
}
//LR
if(balanceFactor > 1 && getBalanceFactor(retNode.left) < 0){
node.left = leftRotate(retNode.left);
return rightRotate(retNode);
}
//RL
if(balanceFactor < -1 && getBalanceFactor(retNode.right) > 0){
node.right = rightRotate(retNode.right);
return leftRotate(retNode);
}
return retNode;
}
六、AVL树完整代码
public class AVLTree<K extends Comparable<K>, V> {
private class Node {
public K key;
public V value;
public Node left, right;
private int height;
public Node(K key, V value) {
this.key = key;
this.value = value;
left = null;
right = null;
this.height = 1; //因为每次节点刚插入都是叶子节点,高度都是1
}
}
private Node root;
private int size;
public AVLTree(){
root = null;
size = 0;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
//判断当前Tree是否为binary search tree
public boolean isBST() {
ArrayList<K> keys = new ArrayList<>();
infixOrder(root, keys); //中序遍历,如果是平衡二叉树,中序遍历就是升序
for (int i = 0; i < keys.size(); i++) {
if (keys.get(i-1).compareTo(keys.get(i)) > 0) { //如果当前node小于前一个node的值,返回false
return false;
}
}
return true;
}
private void infixOrder(Node node, ArrayList<K> keys) {
if (node == null) {
return;
}
infixOrder(node.left, keys);
keys.add(node.key);
infixOrder(node.right, keys);
}
//判断当前tree是否为平衡二叉树
public boolean isBalanced() {
return isBalanced(root);
}
private boolean isBalanced(Node node) {
if (node == null) {
return true;
}
int isBalanced = getBalanceFactor(node);
if (Math.abs(isBalanced) > 1) {
return false;
}
return isBalanced(node.left) && isBalanced(node.right);
}
//获得节点高度
private int getHeight(Node node) {
if (node == null) {
return 0;
} else {
return node.height;
}
}
//获得节点平衡因子
private int getBalanceFactor(Node node) {
if (node == null) {
return 0;
}
return getHeight(node.left) - getHeight(node.right);
}
// 向二分搜索树中添加新的元素e
public void add(K key, V value){
root = add(root, key, value);
}
/**
* 实现右旋
* y为需要右旋的节点
* x为需要旋转节点的左子节点
* z为target1的右子节点
*/
private Node rightRotate(Node y) {
Node x = y.left;
Node z = x.right;
//右旋过程
x.right = y;
y.left = z;
//更新height,只有target和target1的高度才会变化,需要先更新target的height,因为target1的height依赖target
y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
return x;
}
/**
* 实现右旋
* y为需要左旋的节点
* x为需要旋转节点的右子节点
* z为target1的左子节点
*/
private Node leftRotate(Node y) {
Node x = y.right;
Node z = x.left;
//右旋过程
x.left = y;
y.right = z;
//更新height,只有target和target1的高度才会变化,需要先更新target的height,因为target1的height依赖target
y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
return x;
}
// 向以node为根的二分搜索树中插入元素e,递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value){
if(node == null){
size ++;
return new Node(key, value);
}
if(key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if(key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else
node.value = value;
//更新height
node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
//计算平衡因子
int balanceFactor = getBalanceFactor(node);
//平衡维护,balanceFactor > 1表示左子树高度大于右子树的高度,需要右旋
//LL
if (balanceFactor > 1 && getBalanceFactor(node.left) >= 0) {
return rightRotate(node);
}
//平衡维护,balanceFactor > 1表示右子树高度大于左子树的高度,需要左旋
//RR
if (balanceFactor < -1 && getBalanceFactor(node.right) <= 0) {
return leftRotate(node);
}
//LR
if (balanceFactor > 1 && getBalanceFactor(node.left) < 0) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
//RL
if (balanceFactor < -1 && getBalanceFactor(node.right) < 0) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
}
// 看二分AVL树中是否包含元素key
public boolean contains(K key){
return contains(root, key);
}
// 看以node为根的AVL树中是否包含元素value, 递归算法
private boolean contains(Node node, K key){
if(node == null)
return false;
if(key.compareTo(node.key) == 0)
return true;
else if(key.compareTo(node.key) < 0)
return contains(node.left, key);
else // e.compareTo(node.key) > 0
return contains(node.right, key);
}
// 寻找二分搜索树的最小元素
public V minimum(){
if(size == 0)
throw new IllegalArgumentException("BST is empty!");
return minimum(root).value;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node){
if(node.left == null)
return node;
return minimum(node.left);
}
// 寻找二分搜索树的最大元素
public V maximum(){
if(size == 0)
throw new IllegalArgumentException("BST is empty");
return maximum(root).value;
}
// 返回以node为根的二分搜索树的最大值所在的节点
private Node maximum(Node node){
if(node.right == null)
return node;
return maximum(node.right);
}
// 从二分搜索树中删除元素为e的节点
public V remove(K key){
Node node = getNode(root, key);
if (node != null) {
root = remove(root, key);
return node.value;
}
return null;
}
// 删除掉以node为根的二分搜索树中值为e的节点, 递归算法
// 返回删除节点后新的二分搜索树的根
Node remove(Node node, K key){
if( node == null )
return null;
Node retNode; //保证平衡性,用于返回
if( key.compareTo(node.key) < 0 ){
node.left = remove(node.left , key);
retNode = node;
}
else if(key.compareTo(node.key) > 0 ){
node.right = remove(node.right, key);
retNode = node;
}
else{
// 待删除节点左子树为空的情况
if(node.left == null){
Node rightNode = node.right;
node.right = null;
size --;
retNode = rightNode;
}
// 待删除节点右子树为空的情况
else if(node.right == null){
Node leftNode = node.left;
node.left = null;
size --;
retNode = leftNode;
} else {
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = remove(node.right, successor.key);
successor.left = node.left;
node.left = node.right = null;
retNode = successor;
}
}
if (retNode == null) {
return null;
}
//更新height
retNode.height = Math.max(getHeight(retNode.left), getHeight(retNode.right)) + 1;
//计算平衡因子
int balanceFactor = getBalanceFactor(retNode);
//平衡维护,balanceFactor > 1表示左子树高度大于右子树的高度,需要右旋
//LL
if (balanceFactor > 1 && getBalanceFactor(retNode.left) >= 0) {
return rightRotate(retNode);
}
//平衡维护,balanceFactor > 1表示右子树高度大于左子树的高度,需要左旋
//RR
if (balanceFactor < -1 && getBalanceFactor(retNode.right) <= 0) {
return leftRotate(retNode);
}
//LR
if (balanceFactor > 1 && getBalanceFactor(retNode.left) < 0) {
retNode.left = leftRotate(retNode.left);
return rightRotate(retNode);
}
//RL
if (balanceFactor < -1 && getBalanceFactor(retNode.right) < 0) {
retNode.right = rightRotate(retNode.right);
return leftRotate(retNode);
}
return retNode;
}
private Node getNode(Node node, K key) {
if( node == null )
return null;
if( key.compareTo(node.key) < 0 ){
getNode(node.left, key);
} else if(key.compareTo(node.key) > 0){
getNode(node.right, key);
} else {
return node;
}
return null;
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
generateBSTString(root, 0, res);
return res.toString();
}
// 生成以node为根节点,深度为depth的描述二叉树的字符串
private void generateBSTString(Node node, int depth, StringBuilder res){
if(node == null){
res.append(generateDepthString(depth) + "null\n");
return;
}
res.append(generateDepthString(depth) + node.key +"\n");
generateBSTString(node.left, depth + 1, res);
generateBSTString(node.right, depth + 1, res);
}
private String generateDepthString(int depth){
StringBuilder res = new StringBuilder();
for(int i = 0 ; i < depth ; i ++)
res.append("--");
return res.toString();
}
}
七、总结
总的来说要理解AVL树是有点难度的,重点在于理解四种旋转方式,以及旋转后树的节点该如何重新平衡。
1.LL型:旋转后,失衡点的左孩子的右子树,将成为失衡点的左子树。
2.RR型:旋转后,失衡点的右孩子的左子树,将成为失衡点的右子树。
3.LR型:左旋后,z的左子树成为x的右子树;右旋后,z的右子树成为y的左子树。
4.RL型:右旋后,z的右子树成为x的左子树;左旋后,z的左子树成为y的右子树。