完整代码实现
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode {
int key;
struct AVLNode *lChild;
struct AVLNode *rChild;
} AVLNode;
typedef struct AVL {
AVLNode *root;
} AVL;
void initAVL(AVL *avl) {
avl->root = NULL;
}
int getHeight(const AVLNode *p) {
if (p) {
return fmax(getHeight(p->lChild), getHeight(p->rChild)) + 1;
}
return 0;
}
void leftRotate(AVLNode **pp) {
AVLNode *p = *pp;
*pp = (*pp)->rChild;
p->rChild = (*pp)->lChild;
(*pp)->lChild = p;
}
void rightRotate(AVLNode **pp) {
AVLNode *p = *pp;
*pp = (*pp)->lChild;
p->lChild = (*pp)->rChild;
(*pp)->rChild = p;
}
void adjustBalance(AVLNode **pp, const int key) {
if ((*pp)->key > key) {
if (getHeight((*pp)->lChild) - getHeight((*pp)->rChild) == 2) {
if (getHeight((*pp)->lChild->lChild) - getHeight((*pp)->lChild->rChild) == -1) {
leftRotate(&(*pp)->lChild);
}
rightRotate(pp);
}
} else {
if (getHeight((*pp)->lChild) - getHeight((*pp)->rChild) == -2) {
if (getHeight((*pp)->rChild->lChild) - getHeight((*pp)->rChild->rChild) == 1) {
rightRotate(&(*pp)->rChild);
}
leftRotate(pp);
}
}
}
void insertAVL(AVLNode **pp, const int key) {
if (!*pp) {
*pp = (AVLNode *) malloc(sizeof(AVLNode));
(*pp)->key = key;
(*pp)->lChild = (*pp)->rChild = NULL;
} else if ((*pp)->key > key) {
insertAVL(&(*pp)->lChild, key);
adjustBalance(pp, key);
} else if ((*pp)->key < key) {
insertAVL(&(*pp)->rChild, key);
adjustBalance(pp, key);
} else {
printf("结点已存在!\n");
}
}
void deleteAVL(AVLNode **pp, int key) {
if (!*pp) {
printf("结点不存在!\n");
} else if ((*pp)->key > key) {
deleteAVL(&(*pp)->lChild, key);
adjustBalance(pp, key);
} else if ((*pp)->key < key) {
deleteAVL(&(*pp)->rChild, key);
adjustBalance(pp, key);
} else {
AVLNode *p = *pp;
if ((*pp)->lChild && (*pp)->rChild) {
p = (*pp)->lChild;
while (p->rChild) {
p = p->rChild;
}
key = p->key;
deleteAVL(pp, p->key);
(*pp)->key = key;
} else if ((*pp)->lChild) {
*pp = (*pp)->lChild;
free(p);
} else if ((*pp)->rChild) {
*pp = (*pp)->rChild;
free(p);
} else {
*pp = NULL;
free(p);
}
}
}
void inorderAVL(const AVLNode *p) {
if (p) {
inorderAVL(p->lChild);
printf("%-10d%-10d%-10d", p->key, getHeight(p), getHeight(p->lChild) - getHeight(p->rChild));
if(p->lChild){
printf("%-10d",p->lChild->key);
} else{
printf("%-10s","无");
}
if(p->rChild){
printf("%-10d\n",p->rChild->key);
} else{
printf("%-10s\n","无");
}
inorderAVL(p->rChild);
}
}
void test() {
AVL avl;
initAVL(&avl);
int sel, key;
while (true) {
printf("1.插入数据\n2.删除数据\n3.打印信息\n");
scanf("%d", &sel);
switch (sel) {
case 1: {
printf("关键字:");
scanf("%d", &key);
insertAVL(&avl.root, key);
break;
}
case 2: {
printf("关键字:");
scanf("%d", &key);
deleteAVL(&avl.root, key);
break;
}
case 3: {
printf("%-10s%-10s%-10s%-10s%-10s\n", "关键字", "高度", "平衡因子", "左孩子", "右孩子");
inorderAVL(avl.root);
break;
}
default: {
return;
}
}
system("pause");
system("cls");
}
}
int main() {
test();
return 0;
}