c语言创建平衡二叉树
时间: 2023-12-18 10:29:07 浏览: 92
平衡二叉树的详细实现,C++语言,自己动手编程实现的
以下是C语言创建平衡二叉树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义平衡二叉树结点
typedef struct AVLNode {
int data; // 数据域
int height; // 结点高度
struct AVLNode *left; // 左子树指针
struct AVLNode *right; // 右子树指针
} AVLNode, *AVLTree;
// 获取结点高度
int getHeight(AVLTree T) {
if (T == NULL) {
return -1;
} else {
return T->height;
}
}
// 获取两个数中的最大值
int max(int a, int b) {
return a > b ? a : b;
}
// LL旋转
AVLTree LLRotation(AVLTree A) {
AVLTree B = A->left;
A->left = B->right;
B->right = A;
A->height = max(getHeight(A->left), getHeight(A->right)) + 1;
B->height = max(getHeight(B->left), A->height) + 1;
return B;
}
// RR旋转
AVLTree RRRotation(AVLTree A) {
AVLTree B = A->right;
A->right = B->left;
B->left = A;
A->height = max(getHeight(A->left), getHeight(A->right)) + 1;
B->height = max(getHeight(B->right), A->height) + 1;
return B;
}
// LR旋转
AVLTree LRRotation(AVLTree A) {
A->left = RRRotation(A->left);
return LLRotation(A);
}
// RL旋转
AVLTree RLRotation(AVLTree A) {
A->right = LLRotation(A->right);
return RRRotation(A);
}
// 插入结点
AVLTree insert(AVLTree T, int data) {
if (T == NULL) {
T = (AVLTree)malloc(sizeof(AVLNode));
T->data = data;
T->height = 0;
T->left = T->right = NULL;
} else if (data < T->data) {
T->left = insert(T->left, data);
if (getHeight(T->left) - getHeight(T->right) == 2) {
if (data < T->left->data) {
T = LLRotation(T);
} else {
T = LRRotation(T);
}
}
} else if (data > T->data) {
T->right = insert(T->right, data);
if (getHeight(T->right) - getHeight(T->left) == 2) {
if (data > T->right->data) {
T = RRRotation(T);
} else {
T = RLRotation(T);
}
}
}
T->height = max(getHeight(T->left), getHeight(T->right)) + 1;
return T;
}
// 中序遍历
void inorderTraversal(AVLTree T) {
if (T != NULL) {
inorderTraversal(T->left);
printf("%d ", T->data);
inorderTraversal(T->right);
}
}
int main() {
AVLTree T = NULL;
int arr[] = {3, 2, 1, 4, 5, 6, 7, 10, 9, 8};
int len = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < len; i++) {
T = insert(T, arr[i]);
}
inorderTraversal(T); // 输出:1 2 3 4 5 6 7 8 9 10
return 0;
}
```
阅读全文