平衡二叉樹的插入與刪除


主要來源於:數據結構與算法 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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM