C实现红黑树插入删除代码
时间: 2023-06-10 07:05:25 浏览: 128
红黑树插入删除算法
3星 · 编辑精心推荐
好的,我可以为您提供C语言实现的红黑树插入和删除代码。以下是样例代码:
红黑树结构体:
typedef enum { RED, BLACK } nodeColor;
typedef struct rbNodeStructure rbNode;
struct rbNodeStructure {
int key;
rbNode *left, *right, *parent;
nodeColor color;
};
红黑树插入函数:
void insertNode(rbNode **root, rbNode *node) {
rbNode *y = NULL;
rbNode *x = *root;
while (x != NULL) {
y = x;
if (node->key < x->key) {
x = x->left;
}
else {
x = x->right;
}
}
node->parent = y;
if (y == NULL) {
*root = node;
}
else if (node->key < y->key) {
y->left = node;
}
else {
y->right = node;
}
node->left = NULL;
node->right = NULL;
node->color = RED;
insertFixup(root, node);
}
红黑树删除函数:
void deleteNode(rbNode **root, rbNode *node) {
rbNode *x, *y;
if (node->left == NULL || node->right == NULL) {
y = node;
}
else {
y = rbSuccessor(node);
}
if (y->left != NULL) {
x = y->left;
}
else {
x = y->right;
}
if (x != NULL) {
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;
}
if (y != node) {
node->key = y->key;
}
if (y->color == BLACK) {
deleteFixup(root, x, y->parent);
}
free(y);
}
希望这个代码能够帮助到您。
阅读全文