模版题:
#include<bits/stdc++.h>
using namespace std;
typedef struct Node* Bintree;
struct Node
{
int data,height;
Bintree left,right;
};
Bintree root;
Bintree newNode(int data)
{
Bintree Node=(Bintree)malloc(sizeof(struct Node));
Node->data=data;
Node->height=1;
Node->left=NULL;
Node->right=NULL;
return Node;
}
int getHeight(Bintree root)
{
if(root==NULL) return 0;
return root->height;
}
void updateHeight(Bintree root)
{
root->height=max(getHeight(root->left),getHeight(root->right))+1;
}
int getBalanceFactor(Bintree root)
{
return getHeight(root->left)-getHeight(root->right);
}
void L(Bintree &root)
{
Bintree temp=root->right;
root->right=temp->left;
temp->left=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
void R(Bintree &root)
{
Bintree temp=root->left;
root->left=temp->right;
temp->right=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
void insert(Bintree &root,int v)
{
if(root==NULL)
{
root=newNode(v);
return;
}
if(v<root->data)
{
insert(root->left,v);
updateHeight(root);
if(getBalanceFactor(root)==2)
{
if(getBalanceFactor(root->left)==1)
{
R(root);
}
else if(getBalanceFactor(root->left)==-1)
{
L(root->left);
R(root);
}
}
}
else if(v>root->data)
{
insert(root->right,v);
updateHeight(root);
if(getBalanceFactor(root)==-2)
{
if(getBalanceFactor(root->right)==-1)
{
L(root);
}
else if(getBalanceFactor(root->right)==1)
{
R(root->right);
L(root);
}
}
}
}
Bintree create(int data[],int n)
{
Bintree root=NULL;
for(int i=0;i<n;i++)
{
insert(root,data[i]);
}
return root;
}
int main()
{
int n,v;
int data[25];
scanf("%d",&n);
// for(int i=0;i<n;i++)
// {
// scanf("%d",&data[i]);
// }
// root=create(data,n);
// printf("%d",root->data);
for(int i=0;i<n;i++)
{
scanf("%d",&v);
insert(root,v);
}
printf("%d",root->data);
return 0;
}