本文主要介绍二叉平衡树的定义以及它的插入节点工作。
头文件的定义
#ifndef AVL_H_
#define AVL_H_
struct AVL;
typedef struct AVL *Search_tree;
typedef struct AVL *Position;
int Max(int x,int y);
Search_tree create();
void print(Position p,int h);
void traverse(Search_tree t,int h);
int height(Position p);
Position Single_right(Position p);
Position Single_left(Position p);
Position double_right(Position p);
Position double_left(Position p);
Search_tree Insert(Search_tree t,int X);
#endif // AVL_H_
以及相应的结构体定义和操作函数的定义
struct AVL
{
int element;
Position left;
Position right;
int height;
};
int Max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
Search_tree create()
{
Search_tree t_tem=malloc(sizeof(struct AVL));
t_tem->left=NULL;
t_tem->right=NULL;
t_tem->height=-1;
printf("create success\n");
return t_tem;
}
void print(Position p,int h)
{
if(p!=NULL)
{
int i=0;
for(;i<h;i++)
printf(" ");
printf("%d\n",p->element);
}
}
void traverse(Search_tree t,int h)
{
if(t!=NULL)
{
print(t,h);
traverse(t->left,h+1);
traverse(t->right,h+1);
}
}
int height(Position p)
{
if(p==NULL)
return -1;
else
return p->height;
}
Position Single_right(Position p)
{
Position p_tem;
p_tem=p->right;
p->right=p_tem->left;
p_tem->left=p;
p->height=Max(height(p->left),height(p->right))+1;
p_tem->height=Max(height(p_tem->left),height(p_tem->right))+1;
return p_tem;
}
Position Single_left(Position p)
{
Position p_tem;
p_tem=p->left;
p->left=p_tem->right;
p_tem->right=p;
p->height=Max(height(p->left),height(p->right))+1;
p_tem->height=Max(height(p_tem->left),height(p_tem->right))+1;
return p_tem;
}
Position double_right(Position p)
{
Position p_tem;
p_tem=Single_left(p->right);
p->right=p_tem;
p_tem=Single_right(p);
return p_tem;
}
Position double_left(Position p)
{
Position p_tem;
p_tem=Single_right(p->left);
p->left=p_tem;
p_tem=Single_left(p);
return p_tem;
}
Search_tree Insert(Search_tree t,int X)
{
if(t==NULL)
{
Position p_tem=malloc(sizeof(struct AVL));
p_tem->element=X;
p_tem->left=p_tem->right=NULL;
p_tem->height=0;
t=p_tem;
}
else
{
if(X>t->element)
{
t->right=Insert(t->right,X);
if(height(t->right)-height(t->left)>=2)
{
if(X>t->right->element)
t=Single_right(t);
if(X<t->right->element)
t=double_right(t);
}
else
t->height=Max(height(t->left),height(t->right))+1;//如果不进行旋转的话,这个节点的高度要增加1
}
if(X<t->element)
{
t->left=Insert(t->left,X);
if(height(t->left)-height(t->right)>=2)
{
if(X<t->left->element)
t=Single_left(t);
if(X>t->left->element)
t=double_left(t);
}
else
t->height=Max(height(t->left),height(t->right))+1;//如果不进行旋转的话,这个节点的高度要增加1
}
}
return t;
}
主函数
int main()
{
Search_tree t=NULL;
t=Insert(t,10);
t=Insert(t,2);
t=Insert(t,3);
t=Insert(t,5);
t=Insert(t,13);
t=Insert(t,15);
t=Insert(t,14);
traverse(t,0);
return 0;
}
返回结果