平衡二叉树包括:插入,获取高度,更新高度,左旋,右旋,新建结点,获取平衡因子,建立二叉树(只需插入所有结点)
#include<bits/stdc++.h>
using namespace std;
struct node{
int v,height=-1;
node *left,*right;
}*root;
node* newnode(int v){
node* Node=new node;
Node->v=v;
Node->height=1;
Node->left=Node->right=NULL;
return Node;
}
int getheight(node* root){
if(root==NULL)
return 0;
else return root->height;
}
void updateheight(node* root){
root->height=max(getheight(root->left),getheight(root->right))+1;
}
int getBF(node* root){
return getheight(root->left)-getheight(root->right);
}
void L(node* &root){
node* temp=root->right;
root->right=temp->left;
temp->left=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void R(node* &root){
node* temp=root->left;
root->left=temp->right;
temp->right=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void insert(node* &root,int v){
if(root==NULL){
root=newnode(v);
return;
}
if(v<root->v){
insert(root->left,v);
updateheight(root);
if(getBF(root)==2){
if(getBF(root->left)==1) //LL型
R(root);
else if(getBF(root->left)==-1){ //LR型
L(root->left);
R(root);
}
}
}
else{
insert(root->right,v);
updateheight(root);
if(getBF(root)==-2){
if(getBF(root->right)==-1) //RR
L(root);
else if(getBF(root->right)==1){ //RL
R(root->right);
L(root);
}
}
}
}
int main(){
int n,v;
node* root=NULL;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&v);
insert(root,v);
}
printf("%d\n",root->v);
return 0;
}