关于红黑树的理论讲解,网上有很多,大家可以自己找,这里重点在于实现,代码供大家参考。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define RED 0
#define BLACK 1
#define NUM 9
typedef struct RBTNode
{
int key;
struct RBTNode *parent,*left,*right;
int color;
}RBTNode,*RBTree;
RBTree nil,root;
void InitLeafNode()
{
nil =(RBTree)malloc(sizeof(RBTree));
root=(RBTree)malloc(sizeof(RBTree));
nil->color = BLACK;
nil->left = NULL;
nil->right = NULL;
nil->key = -1;
root = nil;
}
RBTree CreatNode(int key,int color)
{
RBTree x;
x=(RBTNode *)malloc(sizeof(RBTNode));
x->color = color;
x->key = key;
x->left = nil;
x->right = nil;
x->parent = NULL;
return x;
}
void LeftRotate(RBTree z) //左旋
{
RBTree y;
y = z->right;
z->right = y->left; //set y
if(y->left != nil)
y->left->parent = z;
y->parent = z->parent;
if(z->parent == nil)
root = y;
else if(z == z->parent->left)
z->parent->left = y;
else
z->parent->right = y;
//Put z on y's left.
y->left = z;
z->parent = y;
}
void RightRotate(RBTree z) //右旋
{
RBTree y;
y = z->left;
z->left = y->right;
if(y->right != nil)
y->right->parent = z;
y->parent = z->parent;
if(z->parent == nil)
root = y;
else if(z == z->parent->left)
z->parent->left = y;
else
z->parent->right = y;
y->right = z;
z->parent = y;
}
void TreeInsert(RBTree z) //插入
{
RBTree x,y;
y = nil;
x = root;
while(x!=nil){ //Find the insertion position.
y = x;
if(z->key<x->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if(y == nil)
root = z;
else{
if(z->key < y->key)
y->left = z;
else
y->right = z;
}
}
void RBTreeInsertFixup(RBTree z) //维护
{
RBTree y;
while(z->parent->color == RED){
if(z->parent == z->parent->parent->left){
y = z->parent->parent->right;
if(y->color == RED){ //case 1.
z->parent->color = BLACK;
z->parent->parent->color = RED;
y->color = BLACK;
z = z->parent->parent;
}
else{
if(z == z->parent->right){ //case 2.
z = z->parent;
LeftRotate(z);
}
z->parent->color = BLACK; //case 3.
z->parent->parent->color = RED;
z = z->parent->parent;
RightRotate(z);
}
}
else{ //symmetry of (case 1,2,3)
y = z->parent->parent->left;
if(y->color == RED){
z->parent->color =BLACK;
z->parent->parent->color =RED;
y->color =BLACK;
z = z->parent->parent;
}
else{
if(z == z->parent->left){
z = z->parent;
RightRotate(z);
}
z->parent->color = BLACK;
z->parent->parent->color = RED;
z = z->parent->parent;
LeftRotate(z);
}
}
}
root->color = BLACK;
}
void RBTreeInsert(RBTree z)
{
TreeInsert(z);
z->left = nil;
z->right = nil;
//z->color = RED;
RBTreeInsertFixup(z);
}
int main(void)
{
RBTree node[NUM];
int key;
int i;
int A[NUM]={8,11,17,15,6,1,22,25,27};
InitLeafNode();
for(i=0;i<NUM;i++){
key=A[i];
node[i]=CreatNode(key,RED);
RBTreeInsert(node[i]);
}
//验证的时候就是打印每个节点的左孩子和右孩子的key,key为-1代表为叶子节点。
printf("The RBT is :\n");
for(i=0;i<NUM;i++)
printf("%d + %d\n",node[i]->left->key,node[i]->right->key);
return 0;
}
vc6.0下验证结果: