#include<stdio.h>
#include<stdlib.h>
//链表类型声明
struct Tree
{
int element;
struct Tree* left;
struct Tree* right;
int height;
};
//计算结点的高度
int height(struct Tree* t)
{
if (t == NULL)
{
return -1;
}
else
{
return t->height;
}
}
//求两个数的最大值
int max(int x, int y)
{
int t;
t = x > y ? x : y;
return t;
}
//单旋转(左)
struct Tree* SingleRotateWithLeft(struct Tree* k2)
{
struct Tree* k1;
k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
k2->height = max(height(k2->left), height(k2->right)) + 1;
k1->height = max(height(k1->left), height(k2->right)) + 1;
return k1;
}
//单旋转(右)
struct Tree* SingleRotateWithRight(struct Tree* k1)
{
struct Tree* k2;
k2 = k1->right;
k1->right = k2->left;
k2->left = k1;
k1->height = max(height(k1->right), height(k1->left)) + 1;
k2->height = max(height(k2->right), height(k1->left)) + 1;
return k2;
}
//双旋转(左)
struct Tree* DoubleRotateWithLeft(struct Tree* k3)
{
k3->left = SingleRotateWithRight(k3->left);
return SingleRotateWithLeft(k3);
}
//双旋转(右)
struct Tree* DoubleRotateWithRight(struct Tree* k1)
{
k1->right = SingleRotateWithLeft(k1->right);
return SingleRotateWithRight(k1);
}
//插入某个元素
struct Tree* insert(int x, struct Tree* t)
{
if (t == NULL)
{
t = (struct Tree*)malloc(sizeof(struct Tree));
if (t == NULL)
{
printf("Out of space!\n");
return NULL;
}
else
{
t->element = x;
t->left = NULL;
t->right = NULL;
t->height = 0;
}
}
else if (x < t->element)
{
t->left = insert(x, t->left);
if (height(t->left) - height(t->right) == 2)
{
if (x < t->left->element)
{
t = SingleRotateWithLeft(t);
}
else
{
t = DoubleRotateWithLeft(t);
}
}
}
else if (x > t->element)
{
t->right = insert(x, t->right);
if (height(t->right) - height(t->left) == 2)
{
if (x > t->right->element)
{
t = SingleRotateWithRight(t);
}
else
{
t = DoubleRotateWithRight(t);
}
}
}
t->height = max(height(t->left), height(t->right)) + 1;
return t;
}
//使用中序遍历打印
void printTree(struct Tree* t)
{
if (t == NULL)
{
printf("Empty tree!\n");
return;
}
//打印左子树
if (t->left != NULL)
{
printTree(t->left);
}
//打印根结点
printf("element is %d\n", t->element);
//打印右子树
if (t->right != NULL)
{
printTree(t->right);
}
}
//主函数
int main(void)
{
struct Tree* root;
//插入某个元素
root = insert(6, NULL);
insert(7, root);
insert(3, root);
insert(8, root);
insert(12, root);
insert(5, root);
insert(16, root);
//使用中序遍历打印
printTree(root);
printf("\n");
printf("树的高度为:%d\n",root->height);
printf("左树的高度为:%d\n", root->left->height);
printf("右树的高度为:%d\n", root->right->height);
return 0;
}
AVL树ADT的实现(C语言链表实现)
于 2023-12-14 14:42:27 首次发布