## 平衡二叉树模板

``````#include<iostream>
using namespace std;
struct node{
int data,height;
node* left;
node* right;
};

node* newNode(int data){
node* root = new node;
root->data = data;
root->height = 1;
root->left = root->right = NULL;
return root;
}

int getHeight(node* root){
if(root == NULL){
return 0;
}
return root->height;
}

int getBalance(node* root){
return getHeight(root->left) - getHeight(root->right);
}

int updateHeight(node* root){
return root->height =  max(getHeight(root->left),getHeight(root->right)) +1;
}

node * search(node* root,int data){
if(root == NULL) return NULL;
if(data == root->data) {
printf("%d\n",root->data);
return root;
}

if(root->data > data)return search(root->left,data);
else return search(root->right,data);
}

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->data){
insert(root->left,v);
updateHeight(root);
int ba = getBalance(root);
if(ba == 2){
int lba = getBalance(root->left);
if(lba == 1){
R(root);
}else if (lba == -1){
L(root->left);
R(root);
}
}
}else{
insert(root->right,v);
updateHeight(root);
int ba = getBalance(root);
if(ba == -2){
int lba = getBalance(root->right);
if(lba == -1){
L(root);
}else if (lba == 1){
R(root->right);
L(root);
}
}
}
}

node* create(int arr[],int n){
node* root = NULL;
for(int i=0;i<n;i++){
insert(root,arr[i]);
}
return root;
}

node * preorder(node* root){
if(root == NULL) return NULL;

printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}

int arr[10000];
int main(){

int N;
scanf("%d",&N);
for(int i=0;i<N;i++){
scanf("%d",&arr[i]);
}

node * root = create(arr, N);

preorder(root);

return 0;
}``````