(⊙v⊙)嗯。。。
原先一直不知道AVL为什么有的时候要旋两次。。。这下懂啦!
AVL详情查看:http://dongxicheng.org/structure/avl/
看图比较好懂。恩。
自己手算一下就知道为什么插入在左子树的右子树上/左子树是不一样的。还是很好理解的,但是不要光看不动手啊啊啊。
然后就是,注意指针也是一个变量,如果把它作为参数放入函数中不带引用的话,那么就算在函数内开辟新空间了,函数结束后指针指向的还是NULL,而且这样会发生内存泄露!
#include <stdio.h>
#include <stdlib.h>
int max(int x,int y){return x>y?x:y;}
class node
{
public:
int val;
node *left,*right;
node(int x):val(x),left(NULL),right(NULL){}
};
class Tree
{
public:
node *root;
void insert(int x,node *&p)
{
if(!p) {p=new node(x);return;}
int h=0;
if(x>p->val)
{
insert(x,p->right);
if(!isbalance(p,h))
{
if(x>p->right->val) l_rotation(p);
else rl_rotation(p);
}
}
if(x<p->val)
{
insert(x,p->left);
if(!isbalance(p,h))
{
if(x<p->left->val) r_rotation(p);
else lr_rotation(p);
}
}
}
bool isbalance(node *tmp,int &h)
{
if(!tmp) return true;
int l=0,r=0;
bool ret=isbalance(tmp->left, l)&&isbalance(tmp->right, r);
if(ret) h=max(l,r)+1;
return ret&&(abs(l-r)<=1);
}
void l_rotation(node *&p)
{
node *tmp=p->right;
p->right=tmp->left;
tmp->left=p;
p=tmp;
}
void r_rotation(node *&p)
{
node *tmp=p->left;
p->left=tmp->right;
tmp->right=p;
p=tmp; //注意这里!!!!! p指向的应该是当前的root节点了
}
void rl_rotation(node *&p)
{
r_rotation(p->right);
l_rotation(p);
}
void lr_rotation(node *&p)
{
l_rotation(p->left);
r_rotation(p);
}
void debug(node *p)
{
if(!p) return;
printf("%d ",p->val);
debug(p->left);
debug(p->right);
}
};
int main()
{
int n,x;
while(scanf("%d",&n)!=EOF)
{
Tree que;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
que.insert(x,que.root);
//que.debug(que.root);printf("\n");
}
printf("%d\n",que.root->val);
}
return 0;
}