二叉树旋转操作,这个只能记一下怎么旋转了
#include<iostream>
#include<algorithm>
using namespace std;
int n;
struct node {
int data;
node *lchild, *rchild;
};
node* Newnode(int x)
{
node* newnode = new node;
newnode->data = x;
newnode->lchild = newnode->rchild = NULL;
return newnode;
}
int Height(node* root)
{
if (root == NULL)return 0;
else return max(Height(root->lchild), Height(root->rchild)) + 1;
}
int getbalance(node* root)
{
return Height(root->lchild) - Height(root->rchild);
}
void R(node*&root)
{
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
root = temp;
}
void L(node*&root)
{
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
root = temp;
}
void insert(node* &root, int x)
{
if (root == NULL)
{
root = Newnode(x);
return;
}
if (x < root->data)
{
insert(root->lchild, x);
if (getbalance(root) == 2)
{
if (getbalance(root->lchild) == 1)
{
R(root);
}
else if (getbalance(root->lchild) == -1)
{
L(root->lchild);
R(root);
}
}
}
else
{
insert(root->rchild, x);
if (getbalance(root) == -2)
{
if (getbalance(root->rchild) == -1)L(root);
else if (getbalance(root->rchild) == 1)
{
R(root->rchild);
L(root);
}
}
}
}
int main()
{
scanf("%d", &n);
node *root = NULL;
for (int i = 0; i < n; i++)
{
int x;
scanf("%d", &x);
insert(root, x);
}
printf("%d", root->data);
return 0;
}