C++实现AVL树的四种旋转

C++实现AVL树的四种旋转,第1张

C++实现AVL树的四种旋转

结构
template
struct AVLNode{
    T data;
    int height;
    AVLNode* lchild, *rchild;
    AVLNode(T dt, AVLNode* l, AVLNode* r):data(dt),lchild(l),rchild(r){}
};

template
class AVLTree{
    public:
        AVLTree(){
            root = nullptr;
        }
        ~AVLTree(){
            Destory(root);
        }
        void Insert(T data){
            _insert(root, data);
        }

        bool Search(T data){
            //return _searchRecursion(root,data);
        
            return _searchNotRecursion(root, data);
        }
        
        bool DeleteData(T data){
            return _deleteData(root, data);
        }

        AVLNode* Left_Rotation(AVLNode* pRoot);       // 左旋
        AVLNode* Right_Rotation(AVLNode* pRoot);      // 右旋
        AVLNode* LR_Rotation(AVLNode* pRoot);         // 先左旋后右旋
        AVLNode* RL_Rotation(AVLNode* pRoot);         // 先右旋后左旋
        
    private:
        AVLNode* root;
        void _insert(AVLNode* pRoot, T data);
        bool _searchRecursion(AVLNode* pRoot, T data);   //递归搜索
        bool _searchNotRecursion(AVLNode* pRoot, T data);//非递归搜索
        void Destory(AVLNode* pRoot);
        bool _deleteData(AVLNode* pRoot, T data);
};
四种旋转场景

通过比较左右子树的高度差(即平衡因子)来反映是否平衡

 

template
AVLNode* AVLTree::Left_Rotation(AVLNode* pRoot)
{
    AVLNode* p = pRoot->rchild;
    pRoot->rchild = p->lchild;
    p->lchild = pRoot;

    pRoot->height = max(pRoot->lchild->height, pRoot->rchild->height)+1;
    p->height = max(p->lchild->height, p->rchild->height)+1;
    return p;
}

template
AVLNode* AVLTree::Right_Rotation(AVLNode* pRoot)
{
    AVLNode* p = pRoot->lchild;
    pRoot->lchild = p->rchild;
    p->rchild = pRoot;

    pRoot->height = max(pRoot->lchild->height, pRoot->rchild->height)+1;
    p->height = max(p->lchild->height, p->rchild->height)+1;
    return p;
}

template
AVLNode* AVLTree::LR_Rotation(AVLNode* pRoot)
{
    Left_Rotation(pRoot->rchild);
    Right_Rotation(pRoot);

    return pRoot->rchild;
}

template
AVLNode* AVLTree::RL_Rotation(AVLNode* pRoot)
{
    Right_Rotation(pRoot->lchild);
    Left_Rotation(pRoot);

    return pRoot->lchild;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5635519.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存