红黑树

寒江独钓的博客(红黑树详细讲解):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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值