1066. Root of AVL Tree (25)

1066. Root of AVL Tree (25)

#include <stdio.h>
#include <malloc.h>
struct AVLTNode
{
    struct AVLTNode *lchild,*rchild;
    int key;
    int height;
}*T;
int Max(int a,int b)
{
    int k=(a>b?a:b);
    return k;
}
int ComputeHeight(struct AVLTNode*T)
{
    if(T)
        return T->height;
    return 0;
}
struct AVLTNode*leftRotation(struct AVLTNode *root)
{
    struct AVLTNode *p=root->rchild;
    root->rchild=p->lchild;
    p->lchild=root;
    p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
    root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
    return p;
}
struct AVLTNode*rightRotation(struct AVLTNode *root)
{
    struct AVLTNode *p=root->lchild;
    root->lchild=p->rchild;
    p->rchild=root;
    p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
    root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
    return p;
}
struct AVLTNode*rightleftRotation(struct AVLTNode *root)
{
    root->rchild=rightRotation(root->rchild);
    return leftRotation(root);
}
struct AVLTNode*leftrightRotation(struct AVLTNode *root)
{
    root->lchild=leftRotation(root->lchild);
    return rightRotation(root);
}
void Insertion(int curkey,struct AVLTNode **T)
{
    if((*T)==NULL)
    {
        (*T)=(struct AVLTNode*)malloc(sizeof(struct AVLTNode));
        (*T)->lchild=(*T)->rchild=NULL;
        (*T)->key=curkey;
        (*T)->height=0;
    }
    else if(curkey<((*T)->key))
    {
        Insertion(curkey,&(*T)->lchild);
        if(ComputeHeight((*T)->lchild)-ComputeHeight((*T)->rchild)==2)
        {
            curkey<(*T)->lchild->key?((*T)=rightRotation(*T)):((*T)=leftrightRotation(*T));
        }
    }
    else if(curkey>(*T)->key)
    {
        Insertion(curkey,&(*T)->rchild);
        if(ComputeHeight((*T)->rchild)-ComputeHeight((*T)->lchild)==2)
        {
            curkey>(*T)->rchild->key?((*T)=leftRotation(*T)):((*T)=rightleftRotation(*T));
        }
    }
    (*T)->height=Max(ComputeHeight((*T)->lchild),ComputeHeight((*T)->rchild))+1;
}
int main()
{
    int n,i;
    T=NULL;
    scanf("%d",&n);
    for(i=0;i<n;++i)
    {
        int curkey;
        scanf("%d",&curkey);
        Insertion(curkey,&T);
    }
    printf("%d",T->key);
    return 0;
}

转载于:https://www.cnblogs.com/xLester/p/7570383.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值