寒江独钓的博客(红黑树详细讲解):http://www.cnblogs.com/yangecnu/p/Introduce-Red-Black-Tree.html
个人尝试写的红黑树代码:
//红黑树:1.一个节点有且仅有一条左子女边为红色。特点1:黑色平衡,从根节点到各个叶节点的路径上,黑色边的条数都相同
#include<iostream>
using namespace std;
const bool RED=true;
const bool BLACK=false;
class node{
public :
int key;
int value;
node* left;
node* right;
bool color;
node(int k,int v,bool c){
left=right=NULL;
key=k;value=v;color=c;
}
};
bool isRed(node* n){
if(n!=NULL){
return n->color==RED;
}
return false;
}
node* rotateLeft(node* n){
if(n!=NULL){
node* n1=n->right;
n->right=n1->left;
n1->left=n;
n1->color=n->color;
n->color=RED;
return n1;
}
return NULL;
}
node* rotateRight(node* n){
if(n!=NULL){
node* n1=n->left;
n->left=n1->right;
n1->right=n;
n1->color=n->color;
n->color=RED;
return n1;
}
return NULL;
}
node* flipColor(node* n){
if(n!=NULL){
n->left->color=BLACK;
n->right->color=BLACK;
n->color=RED;
return n;
}
return NULL;
}
int getValue(node* n,int key){
if(n!=NULL){
if(n->key==key){
return n->value;
}else if(key<n->key){
return getValue(n->left,key);
}else{
return getValue(n->right,key);
}
}
return -1;
}
node* put(node* n,int key,int value){
if(n==NULL){
return new node(key,value,RED);
}else{
if(n->key==key){
n->value=value;
}else if(key<n->key){
n->left=put(n->left,key,value);
}else{
n->right=put(n->right,key,value);
}
//平衡化操作:左旋、右旋、颜色反转
if(isRed(n->right)&&!isRed(n->left)){
n=rotateLeft(n);
}else if(isRed(n->left)&&isRed(n->left->left)){
n=rotateRight(n);
}else if(isRed(n->left)&&isRed(n->right)){
n=flipColor(n);
}
return n;
}
}
int main(){
node* n=put(NULL,1,5);
n=put(n,2,4);
n=put(n,3,3);
n=put(n,4,2);
n=put(n,5,1);
cout<<getValue(n,1)<<" "<<getValue(n,2)<<" "<<getValue(n,3)<<" "<<getValue(n,4)<<" "<<getValue(n,5)<<endl;
return 0;
}
示例:依次插入节点1、2、3、4、5、6、7