c++写一个红黑树代码
时间: 2023-01-15 18:23:45 浏览: 108
这是一段红黑树的 C 代码的例子:
```
#include <stdio.h>
#include <stdlib.h>
// 定义红黑树的节点
typedef struct rbtree_node {
int val;
char color;
struct rbtree_node *left, *right, *parent;
} node;
// 定义红黑树
typedef struct rbtree {
node *root;
} rbtree;
// 创建新节点
node *create_node(int val, char color, node *left, node *right, node *parent) {
node *new_node = (node*) malloc(sizeof(node));
new_node->val = val;
new_node->color = color;
new_node->left = left;
new_node->right = right;
new_node->parent = parent;
return new_node;
}
// 左旋转
void rotate_left(rbtree *tree, 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) {
tree->root = y;
} else if (x == x->parent->left) {
x->parent->left = y;
} else {
x->parent->right = y;
}
y->left = x;
x->parent = y;
}
// 右旋转
void rotate_right(rbtree *tree, node *x) {
node *y = x->left;
x->left = y->right;
if (y->right != NULL) y->right->parent = x;
y->parent = x->parent;
if (x->parent == NULL) {
tree->root = y;
} else if (x == x->parent->right) {
x->parent->right = y;
} else {
x->parent->left = y;
}
y->right = x;
x->parent = y;
}
// 向红黑树中插入新节点
void insert(rbtree *tree, int val) {
node *new_node = create_node(val, 'R', NULL, NULL, NULL);
node *temp = tree->root;
if (temp == NULL) {
tree->root = new_node;
} else {
while (1) {
if (val < temp->val) {
if (temp->left == NULL) {
temp->left = new_node;
new_node->parent = temp;
break;
} else {
temp = temp->left;
}
} else if (val > temp->val)
阅读全文