定义结构体
struct Person
{
struct Person* parent;
struct Person* lchild;
struct Person* rchild;
int m;
};
struct ABLtree
{
struct Person* root;
};
初始化根节点
struct ABLtree* init_tree()
{
struct ABLtree* tree = malloc(sizeof(struct ABLtree));
if (!tree)
{
return NULL;
}
tree->root = NULL;
return tree;
}
添加节点
int compare(struct Person* p1, struct Person* p2)
{
return ((p1->m) - (p2->m));
}
void insertPerson(struct Person* tree, struct Person* data, int(*compare)(struct Person*, struct Person*))
{
if (compare(tree, data) > 0)
{
if (NULL==tree->lchild)
{
tree->lchild = data;
data->parent = tree;
return;
}
insertPerson(tree->lchild, data, compare);
}
else {
if (NULL==tree->rchild)
{
tree->rchild = data;
data->parent = tree;
return;
}
insertPerson(tree->rchild, data, compare);
}
}
void initer(struct ABLtree* mytree, struct Person* data, int(*compare)(struct Person*, struct Person*))
{
if (!tree)
{
return;
}
if (!data)
{
return;
}
if (!compare)
{
return;
}
if (!mytree->root)
{
mytree->root = data;
return;
}
insertPerson((mytree->root), data, compare);
mytree->root=Adjtree(mytree->root);
}
调节平衡
int getHight(struct Person* p)
{
if (!p)
{
return 0;
}
int m = getHight(p->lchild);
int n = getHight(p->rchild);
return m > n ? ++m : ++n;
}
struct Person* rightHand(struct Person* data)
{
struct Person* temp = data;
data = data->lchild;
data->parent = temp->parent;
struct Person* myrchild = data->rchild;
temp->lchild = data->rchild;
if (data->rchild)
{
myrchild->parent = temp;
}
data->rchild = temp;
temp->parent = data;
return data;
}
struct Person* leftHand(struct Person* data)
{
struct Person* temp = data;
data = data->rchild;
data->parent = temp->parent;
struct Person* mylchild = data->lchild;
temp->rchild = data->lchild;
if (mylchild)
{
mylchild->parent = temp;
}
data->lchild = temp;
temp->parent = data;
return data;
}
struct Person* Adjtree(struct Person* tree)
{
if (NULL == tree)
{
return NULL;
}
if (NULL != tree->lchild || NULL != tree->rchild)
{
tree->lchild=Adjtree(tree->lchild);
tree->rchild=Adjtree(tree->rchild);
int l = getHight(tree->lchild);
int r = getHight(tree->rchild);
if ((l - r) > 1)
{
struct Person* data = tree->lchild;
int ll = getHight(data->lchild);
int rr = getHight(data->rchild);
if (rr > ll)
{
tree->lchild=leftHand(data);
}
tree=rightHand(tree);
}else
if ((r - l) > 1)
{
struct Person* data = tree->rchild;
int ll = getHight(data->lchild);
int rr = getHight(data->rchild);
if (ll > rr)
{
tree->rchild=rightHand(data);
}
tree=leftHand(tree);
}
}
return tree;
}