AVL Tree Insert

#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct TNode{
    int value;
    TNode *left=NULL;
    TNode *right=NULL;
    int hight;
}*alvTree,*position;

int getHight(position t){
    if(!t){
        return 0;
    }
    else{
        return t->hight;
    }
}

position LL(position root){
    position A;

    A=root->left;
    root->left=A->right;
    A->right=root;
    root->hight=max(getHight(root->left),getHight(root->right))+1;
    A->hight=max(getHight(A->left),getHight(A->right))+1;
    return A;
}
position RR(position root){
    position A;
    A=root->right;

    root->right=A->left;
    A->left=root;
    root->hight=max(getHight(root->left),getHight(root->right))+1;
    A->hight=max(getHight(A->left),getHight(A->right))+1;
    return A;
}

position LR(position root){
    root->left=RR(root->left);
    root=LL(root);
    return  root;
}

position RL(position root){
    root->right=LL(root->right);
    root=RR(root);
    return root;
}

position Insert(position root,int x){
    if(!root){
        root=new TNode;
        root->hight=1;
        root->value=x;
    }
    else{
        if(x<root->value){
            root->left=Insert(root->left,x);
            if(getHight(root->left)-getHight(root->right)==2){
                if(x<root->left->value){
                    root=LL(root);
                }else if(x>root->left->value){
                    root=LR(root);
                }
            }
        }
        else if(x>root->value){
            root->right=Insert(root->right,x);
            if(getHight(root->left)-getHight(root->right)==-2){
                if(x>root->right->value){
                    root=RR(root);
                }else if(x<root->right->value){
                    root=RL(root);
                }
            }
        }

    }
    root->hight=max(getHight(root->left),getHight(root->right))+1;
        return root;

}


int main(){
    #ifdef ONLINE_JUDGE
    #else
    freopen("F://pat_test//A1066_2.txt","r",stdin);
    #endif // ONLINE_JUDGE

    int n,x;
    position root=NULL;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&x);
        root=Insert(root,x);
    }
    printf("%d",root->value);

    return 0;
}

 

posted @ 2020-06-01 15:29  落地就是一把98K  阅读(187)  评论(0)    收藏  举报