题:点我
题目大意:旋转
A
V
L
AVL
AVL树
在
A
V
L
AVL
AVL操作中主要有两种主要操作,分别是
L
L
LL
LL和
R
R
RR
RR,其中
L
L
LL
LL的旋转本质是希望发生以下的转变
而
R
R
RR
RR的本质是希望发生以下的转变:
如我们熟知的不平衡结构中有以下两种比较普通的形式:
如果想把这两种结构改成平衡的,实际上是对上面两个节点分别进行
R
R
RR
RR(左)与
L
L
LL
LL(右),即:
操作之后变换成:
这个过程的代码:
struct s* ll(struct s*root)
{
struct s* center = root->left;
root->left = center->right;
center->right = root;
return center;
}
struct s* rr(struct s*root)
{
struct s* center = root->right;
root->right = center->left;
center->left = root;
return center;
}
对上面两个节点进行操作之后就可以达到平衡。再来看两种特殊的形式即:
对于这两种形式,首先先对下面两个节点进行
L
L
LL
LL和
R
R
RR
RR转换:
变换之后形成了上面两种普通的形式,最后再做一次
R
R
RR
RR和
L
L
LL
LL转换即可。
这两个过程的代码:
struct s* lr(struct s*root)
{
root->left = rr(root->left);
return ll(root);
}
struct s* rl(struct s*root)
{
root->right = ll(root->right);
return rr(root);
}
A C AC AC代码:
#include<cstdio>
#include<iostream>
#include<stddef.h>
using namespace std;
struct s
{
int num;
struct s*left;
struct s*right;
int height;
};
struct s* ll(struct s*root)
{
struct s* center = root->left;
root->left = center->right;
center->right = root;
return center;
}
struct s* rr(struct s*root)
{
struct s* center = root->right;
root->right = center->left;
center->left = root;
return center;
}
struct s* lr(struct s*root)
{
root->left = rr(root->left);
return ll(root);
}
struct s* rl(struct s*root)
{
root->right = ll(root->right);
return rr(root);
}
struct s* insert(struct s*root, int key)
{
if (root == NULL)
{
root = new s;
root->num = key;
root->left = NULL;
root->right = NULL;
root->height = 0;
return root;
}
if (key < root->num)
{
root->height++;
root->left = insert(root->left, key);
int l = root->left->height + 1;
int r = 0;
if (root->right != NULL)
{
r = root->right->height + 1;
}
if (l - r == 2)
{
if (key < root->left->num)
{
root = ll(root);
}
else
{
root = lr(root);
}
}
}
else
{
root->height++;
root->right = insert(root->right, key);
int r = root->right->height + 1;
int l = 0;
if (root->left != NULL)
{
l = root->left->height + 1;
}
if (r - l == 2)
{
if (key < root->right->num)
{
root = rl(root);
}
else
root = rr(root);
}
}
return root;
}
int main(void)
{
int n;
scanf("%d", &n);
struct s*root = NULL;
for (int i = 0; i < n; i++)
{
int b;
scanf("%d", &b);
root = insert(root, b);
}
printf("%d", root->num);
}
参考代码:
- 柳神的博客