04-树5 Root of AVL Tree

04-树5 Root of AVL Tree
04-树5 Root of AVL Tree_第1张图片
04-树5 Root of AVL Tree_第2张图片
思路分析:这道题思路很清晰,主要就是熟悉二叉平衡树的插入,知道LL,RR,LR,RL旋转的算法就可以解决

#include
using namespace std;

typedef struct AVLTNode* AVLTree;
struct AVLTNode
{
    int height;
    AVLTree left, right;
    int data;
};
AVLTree insert(AVLTree T, int v);
int getHeight(AVLTree T);
AVLTree singleLeftRotation(AVLTree T);
AVLTree doubleLeftRightRotarion(AVLTree T);
AVLTree singleRightRotation(AVLTree T);
AVLTree doubleRightLeftRotation(AVLTree T);
int max(int a, int b);

int main()
{
    int num, i =0;
    int v;
    AVLTree T = NULL;
    cin >> num;
    for(i = 0; i<num; i++)
    {
        cin >> v;
        T = insert(T, v);
    }
    cout << T->data;
    return 0;
}

AVLTree insert(AVLTree T, int v)
{
    if(!T)
    {
        T = (AVLTree)malloc(sizeof(AVLTNode));
        T->data = v;
        T->right = T->left = NULL;
        T->height = 1;
    }else
    {
        if(v < T->data) 
        {
            T->left = insert(T->left, v);
            if(getHeight(T->left)-getHeight(T->right) == 2)
            {
                //结点插在左子树的左边-  左单旋
                if(v < T->left->data) T = singleLeftRotation(T);
                //结点插在左子树的右边-  左-右单旋
                else T = doubleLeftRightRotarion(T);
            }
        }else if(v > T->data)
        {
            T->right = insert(T->right, v);
            if(getHeight(T->left)-getHeight(T->right) == -2)
            {
                //结点插在右子树的右边-  右单旋
                if(v > T->right->data) T = singleRightRotation(T);
                //结点插在右子树的左边-  右-左单旋
                else T = doubleRightLeftRotation(T);
            }
        }
    }
        T->height = max(getHeight(T->left), getHeight(T->right))+1;//不要忘记加一
        return T;
}
int getHeight(AVLTree T)
{
    int maxH,lh,rh;
    if(T)
    {
        lh = getHeight(T->left);
        rh = getHeight(T->right);
        maxH = lh > rh ?lh:rh;
        return (maxH+1);
    }else return 0;

}
int max(int a, int b)
{
    return a>b ? a: b;
}
AVLTree singleLeftRotation(AVLTree T)
{
    AVLTree B;
    B = T->left;
    T->left = B->right;
    B->right = T;
    //更新高度
    T->height = max(getHeight(T->left), getHeight(T->right))+1;
    B->height = max(getHeight(B->left),T->height)+1;
    return B;
}
AVLTree doubleLeftRightRotarion(AVLTree T)
{
    T->left = singleRightRotation(T->left);
    return singleLeftRotation(T);
}
AVLTree singleRightRotation(AVLTree T)
{
    AVLTree B;
    B = T->right;
    T->right = B->left;
    B->left = T;
    //更新高度
    T->height = max(getHeight(T->right), getHeight(T->left))+1;
    B->height = max(getHeight(B->right),T->height)+1;
    return B;
}
AVLTree doubleRightLeftRotation(AVLTree T)
{
    T->right = singleLeftRotation(T->right);
    return singleRightRotation(T);
}

你可能感兴趣的:(数据结构与算法第二版,数据结构第二版题目集)