平衡二叉树的插入与删除

主要来源于:数据结构与算法 java语言描述
适合哪些人阅读:如果您已经对平衡二叉树的概念有一定了解,并且对插入时逻辑有一定了解,这篇文章提供不完整的代码实现。
阅读时间: 10分钟

平衡因子

定义:某节点的左子树与右子树的高度(深度)差即为该节点的平衡因子(BF,Balance Factor),平衡二叉树中不存在平衡因子大于 1 的节点。在一棵平衡二叉树中,节点的平衡因子只能取 0 、1 或者 -1 ,分别对应着左右子树等高,左子树比较高,右子树比较高。

AVL树定义

平衡二叉查找树:简称平衡二叉树、 AVL 树,是一种二叉查找树
它具有如下几个性质:
1.可以是空树。
2.假如不是空树,任何一个结点的左子树与右子树都是平衡二叉树,并且高度之差的绝对值不超过 1。|BF|<=1

节点表示

public class AVLNode<T> {
    int height;
    AVLNode left;
    AVLNode right;
    T val;

    public AVLNode(T val AVLNode left, AVLNode right) {
        this.left = left;
        this.right = right;
        this.val = val;
    }
    public AVLNode(int val){
       this(T val,null,null);
    }  
}

二叉查找树定义

插入操作

priate AVLNode<T> insert(T x ,AVLNode<T> t){
    if(t == null) return new AVLNode(x , null ,null);
    
    int cmp = x.compareTo(t.val);
    if(cmp < 0)
        t.left = insert(x, t.left);
    else if(cmp>0)
        t.right = insert(x , t.right);
    else
        ;
   return balance(t);
}

private AVLNode<T> balance( AVLNode<T> t){
    if(t == null) return t;
    if(height(t.left) - height(t.right) > 1){
        if(height(t.left.left) >= height(t.left.right)){
            t = rotateWithLeftChild( t );
        }else{
            t = doubleWithLeftChild( t );
        }
    }else{
        if(height(t.right.right) >= height(t.right.left)){
            t = rotateWithRightChild( t );
        }else{
            t = doubleWithRightChild( t );
        }
    }
    t.height = Max.max(height(t.left),height(t.right)) + 1;
    return t;
}

private AVLNode<T> rotateWithLeftChild(AVLNode<T> k2){
    AVLNode<T> k1 = k2.left;
    k2.left = k1.left;
    k1.right = k2;
    k2.height = Math.max(height(k2.left) , height(k2.right) ) + 1;
    k1.height = Math.max(height(k1.left) , height(k1.right) ) + 1;
}
private AVLNode<T> doubleWithLeftChild(AVLNode<T> k3){
    k3.left = rotateWithRightChild(k3.left);
    return rotateWithLeftChild(k3);
}

删除操作

private AVLNode<T> remove(T x , ABLNode<T> t){
    if(t == null) return t;
    in cmp = x.compareTo(t.val);
    if(cmp < 0)
        t.left = remove(x , t.left);
    else if(cmp > 0){
        t.right = remove(x , t.right);
    else if(t.left != null && t.right != null)
        t.val = findMin(t.right).val;
       t.right = remove(t.val , t.right);
    } 
    else 
        t =(t.left != null)? t.left : t.right;
    return balance(t);
}
原文地址:https://www.cnblogs.com/0ffff/p/11113833.html