敲这个题时,预备知识是知道四种旋转方式,分别是LL、RR、LR、RL,对应每一种的变换方式要做到会旋转,会写关键的代码
这个题是参照一篇博客写的,然后自己又理解了一遍。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
struct node *l, *r;
int data, d;
};
int max(int a,int b)
{
if(a < b)
return b;
else return a;
}
int deep(struct node *root)
{
if(root == NULL)
return -1;
else return root->d;
}
struct node *LL(struct node *root)
{
struct node *p;
p = root->l;
root->l = p->r;
p->r = root;
root->d = max(deep(root->l), deep(root->r)) + 1;
return p;
};
struct node *RR(struct node *root)
{
struct node *p;
p = root->r;
root->r = p->l;
p->l = root;
root->d = max(deep(root->l),deep(root->r)) + 1;
return p;
};
struct node *LR(struct node *root)
{
/*//如果用以下代码的话会出现超时的错误,因为如果树越来越庞大的时候
每次都是这样处理数据就会很麻烦,也很耗时。要用RR和LL时的结果。
struct node *p;
p = root->l;
root->l = p->r->r;
p->r = p->r->l;
p->r->l = p;
p->r->r = root;
root->d = max(deep(root->l),deep(root->r)) + 1;
return p;*/
root->l = RR(root->l);
root = LL(root);
return root;
};
struct node *RL(struct node *root)
{
/*struct node *p;
p = root->r;
p->l = p->l->r;
root->r = p->l->l;
p->l->r = p;
p->l->l = root;
root->d = max(deep(root->l),deep(root->r)) + 1;
return p;*/
root->r = LL(root->r);
root = RR(root);
return root;
};
struct node *creat(int x,struct node *root)
{
if(root == NULL)
{
root = (struct node *)malloc(sizeof(struct node));
root->data = x;
root->d = 0;
root->l = NULL;
root->r = NULL;
}
else
{
if(x < root->data)
{
root->l = creat(x,root->l);
if(deep(root->l) - deep(root->r) > 1)
{
if(x < root->l->data)
root = LL(root);
else root = LR(root);
}
}
else if(x > root->data)
{
root->r = creat(x,root->r);
if(deep(root->r) - deep(root->l) > 1)
{
if(x > root->r->data)
root = RR(root);
else root = RL(root);
}
}
}
root->d = max(deep(root->l),deep(root->r)) + 1;
return root;
};
int main()
{
struct node *root;
int n, i,x;
scanf("%d",&n);
root = NULL;
for(i = 0;i < n;i++)
{
scanf("%d",&x);
root = creat(x,root);
}
printf("%d\n",root->data);
return 0;
}