使用C语言实现一个红黑树
时间: 2024-05-07 12:23:31 浏览: 65
红黑树是一种平衡二叉搜索树,它的操作包括插入、删除和查找。下面是一个使用C语言实现红黑树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef enum { RED, BLACK } Color;
typedef struct Node {
int key;
Color color;
struct Node *left, *right, *parent;
} Node;
Node *createNode(int key) {
Node *node = (Node *)malloc(sizeof(Node));
node->key = key;
node->color = RED;
node->left = node->right = node->parent = NULL;
return node;
}
void leftRotate(Node **root, Node *x) {
Node *y = x->right;
x->right = y->left;
if (y->left != NULL)
y->left->parent = x;
y->parent = x->parent;
if (x->parent == NULL)
*root = y;
else if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
}
void rightRotate(Node **root, Node *y) {
Node *x = y->left;
y->left = x->right;
if (x->right != NULL)
x->right->parent = y;
x->parent = y->parent;
if (y->parent == NULL)
*root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
x->right = y;
y->parent = x;
}
void insertFixup(Node **root, Node *z) {
while (z->parent != NULL && z->parent->color == RED) {
if (z->parent == z->parent->parent->left) {
Node *y = z->parent->parent->right;
if (y != NULL && y->color == RED) {
z->parent->color = BLACK;
y->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
} else {
if (z == z->parent->right) {
z = z->parent;
leftRotate(root, z);
}
z->parent->color = BLACK;
z->parent->parent->color = RED;
rightRotate(root, z->parent->parent);
}
} else {
Node *y = z->parent->parent->left;
if (y != NULL && y->color == RED) {
z->parent->color = BLACK;
y->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
} else {
if (z == z->parent->left) {
z = z->parent;
rightRotate(root, z);
}
z->parent->color = BLACK;
z->parent->parent->color = RED;
leftRotate(root, z->parent->parent);
}
}
}
(*root)->color = BLACK;
}
void insert(Node **root, int key) {
Node *z = createNode(key);
Node *y = NULL;
Node *x = *root;
while (x != NULL) {
y = x;
if (z->key < x->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if (y == NULL)
*root = z;
else if (z->key < y->key)
y->left = z;
else
y->right = z;
insertFixup(root, z);
}
void inorderTraversal(Node *node) {
if (node == NULL)
return;
inorderTraversal(node->left);
printf("%d ", node->key);
inorderTraversal(node->right);
}
int main() {
Node *root = NULL;
int keys[] = {10, 20, 30, 15, 18, 25, 40};
int n = sizeof(keys) / sizeof(keys[0]);
for (int i = 0; i < n; i++)
insert(&root, keys[i]);
inorderTraversal(root);
return 0;
}
```
这个示例代码实现了红黑树的插入操作和中序遍历操作。在插入新节点时,需要按照二叉搜索树的规则找到它应该插入的位置,然后根据红黑树的规则进行修复。修复过程中需要进行左旋和右旋操作,以保证树的平衡性。在最后输出中序遍历结果时,可以看到红黑树的特征:所有红色节点都有黑色父节点,树的高度比普通二叉搜索树低,从而提高了插入、删除和查找的效率。
阅读全文