红黑树算法

#include <iostream>
#include <algorithm>
using namespace std;
typedef struct node
{
	int key;
	node* lchild;
	node* rchild;
	node* parent;
	int color;
	int flag;
} *PNODE,NODE;
//Create a node
PNODE create_node(int key,int color=0)
{
	PNODE p=new NODE;
	p->key=key;
	p->lchild=p->rchild=p->parent=NULL;
	p->color=color;
	p->flag=-1;
	return p;
}
//Insert a node
PNODE insert_node(PNODE p,PNODE root)
{
	if(p->key>root->key)
		if(root->rchild!=NULL)return insert_node(p,root->rchild);
		else {root->rchild=p;p->parent=root;p->flag=1;return p;}
	else if(root->lchild!=NULL)return insert_node(p,root->lchild);
	else {root->lchild=p;p->parent=root;p->flag=0;return p;}
}
//Adjust the tree
void new_balance(PNODE p,PNODE p_root)
{	
	if(p->parent->color)return;
	PNODE parent=p->parent,grand_parent=p->parent->parent,great_grand_parent=p->parent->parent->parent,temp;
	if(p->flag==1 && parent->flag==0)
	{
		//先左旋,后右旋
		grand_parent->flag?great_grand_parent->rchild=p,(PNODE)(p->flag=1):(great_grand_parent->lchild=p,(PNODE)(p->flag=0));
		p->lchild?p->lchild->parent=parent,p->lchild->flag=1:0;
		p->rchild?p->rchild->parent=parent,p->rchild->flag=0:0;
		parent->parent=p;
		parent->rchild=p->lchild;
		parent->color=1;
		grand_parent->parent=p;
		grand_parent->lchild=p->rchild;
		grand_parent->flag=1;
		p->parent=great_grand_parent;
		p->lchild=parent;
		p->rchild=grand_parent;
	}
	else if(p->flag==1 && parent->flag==1)
	{
		//直接左旋
		grand_parent->rchild=p;
		parent->parent=p;
		parent->flag=0;
		parent->rchild=p->lchild;
		p->lchild?p->lchild->parent=parent,p->lchild->flag=1:0;
		p->parent=grand_parent;
		p->lchild=parent;
		p->color=1;
	}
	else if(p->flag==0 && parent->flag==0)
	{
		//直接右旋
		grand_parent->lchild=p;
		parent->parent=p;
		parent->flag=1;
		parent->lchild=p->rchild;
		p->rchild?p->rchild->parent=parent,p->rchild->flag=0:0;
		p->parent=grand_parent;
		p->rchild=parent;
		p->color=1;
	}
	else
	{
		//先右旋,后左旋
		grand_parent->flag?great_grand_parent->rchild=p,(PNODE)(p->flag=1):(great_grand_parent->lchild=p,(PNODE)(p->flag=0));
		p->lchild?p->lchild->parent=grand_parent,p->lchild->flag=1:0;
		p->rchild?p->rchild->parent=parent,p->rchild->flag=0:0;
		parent->parent=p;
		parent->rchild=p->lchild;
		parent->color=1;
		grand_parent->parent=p;
		grand_parent->lchild=p->rchild;
		grand_parent->flag=0;
		p->parent=great_grand_parent;
		p->rchild=parent;
		p->lchild=grand_parent;
	}
	p_root->lchild->color=1;
	new_balance(p,p_root);
}
//Traverse all of the elements
void traverse(PNODE p)
{
	if(!p)return;
	else
	{
		cout<<p->key<<endl;
		traverse(p->lchild);
		traverse(p->rchild);
	}
}
int main()
{
	PNODE root=create_node(15,1);
	PNODE p_root=create_node(0,1);
	root->parent=p_root;
	root->flag=0;
	p_root->lchild=root;
	root->flag=0;
	for(int i=0;i<20;i++)
	{
		new_balance(insert_node(create_node(i+10),p_root->lchild),p_root);
	}
	traverse(p_root->lchild);
	return 0;
}
posted @ 2013-09-05 22:44  SKY_VIEW  阅读(554)  评论(0编辑  收藏  举报