#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;
}
PAT甲1066 Root of AVL Tree(25 分)
最新推荐文章于 2021-09-03 01:06:49 发布