问题链接: https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int v, h;//v为结点权值,h为当前子树高度
node *lchild, *rchild;
};
//生成一个新结点
node *newNode(int x){
node *Node = new node;
Node -> v = x;//结点权值
Node -> h = 1;//结点高度
Node -> lchild = NULL;
Node -> rchild = NULL;
return Node;
}
//获取以root为根结点的子树的当前高度
int height(node *root){
if(root == NULL)
return 0;
else
return root->h;
}
//计算结点root的平衡因子
int Balance(node *root){
return height(root->lchild) - height(root->rchild);
}
//更新结点root的高度
void upheight(node *root){
root->h = max(height(root->lchild), height(root->rchild)) + 1;
}
//左旋(Left Rotation)
void Left(node *&root){
node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
//更新高度
upheight(root);
upheight(temp);
root = temp;
}
//右旋(Right Rotation)
void Right(node *&root){
node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
//更新高度
upheight(root);
upheight(temp);
root = temp;
}
//插入权值为x的结点
void insert(node *&root, int x){
if(root == NULL){
root = newNode(x);
return;
}
if(x < root->v){
insert(root->lchild, x);
upheight(root);
if(Balance(root) == 2){//左右子树高度差2,则需要旋转
if(Balance(root->lchild) == 1)//LL型
Right(root);
else if(Balance(root->lchild) == -1) //LR型
{
Left(root->lchild);
Right(root);
}
}
}else{
insert(root->rchild, x);
upheight(root);
if(Balance(root) == -2){
if(Balance(root->rchild) == -1)//RR型
Left(root);
else if(Balance(root->rchild) == 1)//RL型
{
Right(root->rchild);
Left(root);
}
}
}
}
int main(){
int n, x;
cin >> n;
node *root = NULL;
for(int i = 0; i < n; i++){
cin >> x;
insert(root, x);
}
cout << root->v;
return 0;
}