PAT甲1066 Root of AVL Tree(25 分)

#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;

struct node
{
    int data;
    int h;
    node* lchild;
    node* rchild;
};

node* newnode(int x)
{
    node* root=new node;
    root->lchild=NULL;
    root->rchild=NULL;
    root->data=x;
    root->h=1;
    return root;
}

int geth(node* root)
{
    if(root==NULL)return 0;
    else return root->h;
}

void updateh(node* root)
{
    root->h=max(geth(root->lchild),geth(root->rchild))+1;
}

int getb(node* root)
{
    return geth(root->lchild)-geth(root->rchild);
}

void L(node* &root)
{
     node* temp=root->rchild;
     root->rchild=temp->lchild;
     temp->lchild=root;
     root=temp;
     updateh(root->lchild);
     updateh(root);
}

void R(node* &root)
{
    node* temp=root->lchild;
    root->lchild=temp->rchild;
    temp->rchild=root;
    root=temp;
    updateh(root->rchild);
    updateh(root);
}

void insert(node* &root,int x)
{
    if(root==NULL)
    {
        root=newnode(x);
        return;
    }
    else
    {
        if(x<root->data)
        {
            insert(root->lchild,x);
            updateh(root);
            if(getb(root)==2)
            {
                if(getb(root->lchild)==1)
                {
                    R(root);
                }
                else if(getb(root->lchild)==-1)
                {
                    L(root->lchild);
                    R(root);
                }
            }
        }
        else
        {
            insert(root->rchild,x);
            updateh(root);
            if(getb(root)==-2)
            {
                if(getb(root->rchild)==-1)
                {
                    L(root);
                }
                else if(getb(root->rchild)==1)
                {
                    R(root->rchild);
                    L(root);
                }
            }
        }
    }
}

node* create(int data[],int n)
{
    node* root=NULL;
    for(int i=0;i<n;i++)
    {
        insert(root,data[i]);
    }
    return root;
}

int N,A[110];

int main()
{
    scanf("%d",&N);
    for(int i=0;i<N;i++)
    {
        scanf("%d",&A[i]);
    }
    node* root=create(A,N);
    printf("%d",root->data);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/82192951