PAT甲1066. Root of AVL Tree (25)

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

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

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

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

int getbfactor(node* root)
{
    return getheight(root->lchild)-getheight(root->rchild);
}

void updateheight(node* root)
{
    root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
}

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

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

void insert(node* &root,int x)
{
    if(root==NULL)
    {
        root=newNode(x);
        return;
    }
    if(x<root->data)
    {
        insert(root->lchild,x);
        updateheight(root);
        if(getbfactor(root)==2)
        {
            if(getbfactor(root->lchild)==1)
            {
                R(root);
            }
            else if(getbfactor(root->lchild)==-1)
            {
                L(root->lchild);
                R(root);
            }
        }
    }
    else if(x>root->data)
    {
        insert(root->rchild,x);
        updateheight(root);
        if(getbfactor(root)==-2)
        {
            if(getbfactor(root->rchild)==-1)
            {
                L(root);
            }
            else if(getbfactor(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 main()
{
    int N,a[30];
    scanf("%d",&N);
    for(int i=0;i<N;i++)
    {
        scanf("%d",&a[i]);
    }
    node* root=Create(a,N);
    printf("%d\n",root->data);
    system("pause");
    return 0;
}

猜你喜欢

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