#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int data,leftheight,rightheight;
node*lchild,*rchild;
};
void insert(node*&root,int i)
{
if(root==NULL){
root=new node;
root->data=i;
root->lchild=root->rchild=NULL;
root->leftheight=root->rightheight=0;
}
else{
if(i>root->data){
insert(root->rchild,i);
root->rightheight=max(root->rchild->leftheight,root->rchild->rightheight)+1;
}
else{
insert(root->lchild,i);
root->leftheight=max(root->lchild->leftheight,root->lchild->rightheight)+1;
}//插入节点,以及 高度更新
if(root->leftheight-root->rightheight==2){//左边
if(root->lchild->leftheight>root->lchild->rightheight){//左边
node*a=root;
node*b=root->lchild;
root=b;
a->lchild=b->rchild;
a->leftheight=b->rightheight;
b->rchild=a;
b->rightheight++;
}
else{//左右
node*a=root;
node*b=root->lchild;
node*c=root->lchild->rchild;
root=c;
b->rchild=c->lchild;
b->rightheight=c->leftheight;
a->lchild=c->rchild;
a->leftheight=c->rightheight;
c->lchild=b;
c->rchild=a;
c->leftheight=b->leftheight+1;
c->rightheight=a->rightheight+1;
}
}
else if(root->leftheight-root->rightheight==-2){//右边
if(root->rchild->rightheight>root->rchild->leftheight){//左边
node*a=root;
node*b=root->rchild;
root=b;
a->rchild=b->lchild;
a->rightheight=b->leftheight;
b->lchild=a;
b->leftheight++;
}
else{//左右
node*a=root;
node*b=root->rchild;
node*c=root->rchild->lchild;
root=c;
a->rchild=c->lchild;
a->rightheight=c->leftheight;
b->lchild=c->rchild;
b->leftheight=c->rightheight;
c->lchild=a;
c->rchild=b;
c->leftheight=a->leftheight+1;
c->rightheight=b->rightheight+1;
}
}
}
}
int main()
{
int N,i;
node*Tree=NULL;
cin>>N;
while(N--){
cin>>i;
insert(Tree,i);
}
cout<<Tree->data;
}
1066 Root of AVL Tree
于 2023-03-05 21:10:40 首次发布