#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1001;
struct node
{
int data,height;
node*l,*r;
};
int getHeight(node* root)
{
if(root == NULL) return 0;
return root->height;
}
int getBalance(node* root)
{
return (getHeight(root->l) - getHeight(root->r));
}
void upHeight(node* root)
{
root->height = max(getHeight(root->l),getHeight(root->r))+1;
}
void LeftRotation(node*&root)
{
node*temp = root->r;
root->r = temp->l;
temp->l = root;
upHeight(root);
upHeight(temp);
root = temp;
}
void rightRotation(node*&root)
{
node*temp = root->l;
root->l = temp->r;
temp->r = root;
upHeight(root);
upHeight(temp);
root = temp;
}
node* newNode(int data)
{
node*temp = new node;
temp->data = data;
temp->height = 1;
temp->l = temp->r = NULL;
return temp;
}
void insertT(node* &root,int data)
{
if(root == NULL)
{
root = newNode(data);
return;
}
if(data < root->data)
{
insertT(root->l,data);
upHeight(root);
if(getBalance(root) == 2)
{
if(getBalance(root->l) == 1)
rightRotation(root);
else if(getBalance(root->l) == -1)
{
LeftRotation(root->l);
rightRotation(root);
}
}
}
else
{
insertT(root->r,data);
upHeight(root);
if(getBalance(root) == -2)
{
if(getBalance(root->r) == -1)
LeftRotation(root);
else if(getBalance(root->r) == 1)
{
rightRotation(root->r);
LeftRotation(root);
}
}
}
}
int main()
{
int n;
scanf("%d",&n);
node*root = NULL;
for(int i = 0;i<n;i++)
{
int temp;
scanf("%d",&temp);
insertT(root,temp);
}
printf("%d",root->data);
return 0;
}
1066 Root of AVL Tree (25 分)(******)(avl树的建立全过程,左旋右旋)
最新推荐文章于 2022-02-27 20:16:38 发布