红黑BST

摘自:《算法:C语言实现 (第1~4部分)

去掉了维护节点数的函数 fixN(h),添加了打印树结构的函数。

//RB_BST.h
typedef char Item;
typedef struct STnode *link;
void STinit();
void show(int h);
void STinsert(Item item);


//RB_BST.cpp
#include <iostream>
#include "RB_BST.h"
using namespace std;

#define NULLitem  (-1)

struct STnode
{
	Item item;
	link left, right;
	int N;
	int red;
};

static link head, z;

link NEW(Item item, link l, link r, int N, int color)
{
	link x = (link)malloc(sizeof(*x));
	x->item = item;
	x->left = l;
	x->right = r;
	x->N = N;
	x->red = color;
	return x;
}

void STinit()
{
	head = (z = NEW(NULLitem, 0, 0, 0, 0));
}

void printnode(link x, int h)
{
	int i;
	for(i = 0; i < h; i++)
		printf("     ");
	if(x == z)
		printf("*\n");
	else
		printf("%c(%d)\n", x->item, x->red);
}

void show_tree(link x, int h)
{
	if(z == x) {
		printnode(z, h);
		return;
	}
	show_tree(x->right, h + 1);
	printnode(x, h);
	show_tree(x->left, h + 1);
}

void show(int h)
{
	show_tree(head, h);
}

link rotR(link h)
{
	link x = h->left;   h->left = x->right;  x->right = h;     
	return x;
}

link rotL(link h)
{
	link x = h->right; h->right = x->left; x->left = h;
	return x;
}

link RBinsert(link h, Item item, int sw)
{
	if(h == z)  return NEW(item, z, z, 1, 1);
	if(h->left->red && h->right->red)
		{ h->red = 1; h->left->red = 0; h->right->red = 0;}
	if(item < h->item)
	{
		h->left = RBinsert(h->left, item, 0);
		if(h->red && h->left->red && sw)   h = rotR(h);
		if(h->left->red && h->left->left->red)
			{ h = rotR(h); h->red = 0; h->right->red = 1;}
	}
	else
	{
		h->right = RBinsert(h->right, item, 1);
		if(h->red && h->right->red && !sw)	 h = rotL(h);
		if(h->right->red && h->right->right->red)
			{ h = rotL(h); h->red = 0; h->left->red = 1;}
	}
	return h;
}

void STinsert(Item item)
{
	head = RBinsert(head, item, 0);
	head->red = 0;
}

//main.cpp
#include <iostream>
#include "RB_BST.h"
using namespace std;

int main(int argc, char *argv[])
{
	char c;
	STinit();
	while ((c = getchar()) != EOF)
	{
		if(c == ' ' || c == '\t' || c == '\n')
			continue;

		STinsert(c);
		cout << endl;
		show(0);
		cout << endl;
	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值