平衡二叉树c语言实现代码
时间: 2023-12-12 19:35:44 浏览: 45
以下是一个简单的C语言实现平衡二叉树的代码,其中包括了对于四种不平衡情况的处理和递归添加新数据的方法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
int height;
} node;
int height(node *n) {
if (n == NULL) {
return 0;
}
return n->height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
node *new_node(int data) {
node *n = (node *)malloc(sizeof(node));
n->data = data;
n->left = NULL;
n->right = NULL;
n->height = 1;
return n;
}
node *right_rotate(node *y) {
node *x = y->left;
node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
node *left_rotate(node *x) {
node *y = x->right;
node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int get_balance(node *n) {
if (n == NULL) {
return 0;
}
return height(n->left) - height(n->right);
}
node *insert(node *n, int data) {
if (n == NULL) {
return new_node(data);
}
if (data < n->data) {
n->left = insert(n->left, data);
} else if (data > n->data) {
n->right = insert(n->right, data);
} else {
return n;
}
n->height = 1 + max(height(n->left), height(n->right));
int balance = get_balance(n);
if (balance > 1 && data < n->left->data) {
return right_rotate(n);
}
if (balance < -1 && data > n->right->data) {
return left_rotate(n);
}
if (balance > 1 && data > n->left->data) {
n->left = left_rotate(n->left);
return right_rotate(n);
}
if (balance < -1 && data < n->right->data) {
n->right = right_rotate(n->right);
return left_rotate(n);
}
return n;
}
void pre_order(node *n) {
if (n != NULL) {
printf("%d ", n->data);
pre_order(n->left);
pre_order(n->right);
}
}
int main() {
node *root = NULL;
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);
printf("Preorder traversal of the constructed AVL tree is: \n");
pre_order(root);
return 0;
}
```