帮我实现一个 c++ AVL树
时间: 2023-03-24 22:02:37 浏览: 180
好的,我可以帮您实现一个 C AVL树。以下是代码示例:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode {
int data;
int height;
struct AVLNode *left;
struct AVLNode *right;
} AVLNode;
int max(int a, int b) {
return (a > b) ? a : b;
}
int height(AVLNode *node) {
if (node == NULL) {
return ;
}
return node->height;
}
AVLNode *newNode(int data) {
AVLNode *node = (AVLNode *) malloc(sizeof(AVLNode));
node->data = data;
node->height = 1;
node->left = NULL;
node->right = NULL;
return node;
}
AVLNode *rightRotate(AVLNode *y) {
AVLNode *x = y->left;
AVLNode *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;
}
AVLNode *leftRotate(AVLNode *x) {
AVLNode *y = x->right;
AVLNode *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 getBalance(AVLNode *node) {
if (node == NULL) {
return ;
}
return height(node->left) - height(node->right);
}
AVLNode *insert(AVLNode *node, int data) {
if (node == NULL) {
return newNode(data);
}
if (data < node->data) {
node->left = insert(node->left, data);
} else if (data > node->data) {
node->right = insert(node->right, data);
} else {
return node;
}
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
if (balance > 1 && data < node->left->data) {
return rightRotate(node);
}
if (balance < -1 && data > node->right->data) {
return leftRotate(node);
}
if (balance > 1 && data > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && data < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void preOrder(AVLNode *root) {
if (root != NULL) {
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}
int main() {
AVLNode *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");
preOrder(root);
return ;
}
```
这是一个简单的 AVL 树实现,包括插入和前序遍历。您可以根据需要进行修改和扩展。
阅读全文