您的位置:首页 > 编程语言 > C语言/C++

第十四章 红黑树——C++代码实现

2014-11-05 18:16 489 查看

红黑树的介绍

红黑树(Red-Black Tree,简称R-B Tree),它一种特殊的二叉查找树。
红黑树是特殊的二叉查找树,意味着它满足二叉查找树的特征:任意一个节点所包含的键值,大于等于左孩子的键值,小于等于右孩子的键值。
除了具备该特性之外,红黑树还包括许多额外的信息。

红黑树的每个节点上都有存储位表示节点的颜色,颜色是红(Red)或黑(Black)。
红黑树的特性:
(1) 每个节点或者是黑色,或者是红色。
(2) 根节点是黑色。
(3) 每个叶子节点是黑色。 [注意:这里叶子节点,是指为空的叶子节点!]
(4) 如果一个节点是红色的,则它的子节点必须是黑色的。
(5) 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。

关于它的特性,需要注意的是:
第一,特性(3)中的叶子节点,是只为空(NIL或null)的节点。
第二,特性(5),确保没有一条路径会比其他路径长出俩倍。因而,红黑树是相对是接近平衡的二叉树。

红黑树示意图如下:

#include <iostream>
#include "RBTree.h"
using namespace std;

int main()
{
int a[]= {10, 40, 30, 60, 90, 70, 20, 50, 80};
int check_insert=0;    // "插入"动作的检测开关(0,关闭;1,打开)
int check_remove=0;    // "删除"动作的检测开关(0,关闭;1,打开)
int i;
int ilen = (sizeof(a)) / (sizeof(a[0])) ;
RBTree<int>* tree=new RBTree<int>();

cout << "== 原始数据: ";
for(i=0; i<ilen; i++)
cout << a[i] <<" ";
cout << endl;

for(i=0; i<ilen; i++)
{
tree->insert(a[i]);
// 设置check_insert=1,测试"添加函数"
if(check_insert)
{
cout << "== 添加节点: " << a[i] << endl;
cout << "== 树的详细信息: " << endl;
tree->print();
cout << endl;
}

}

cout << "== 前序遍历: ";
tree->preOrder();

cout << "\n== 中序遍历: ";
tree->inOrder();

cout << "\n== 后序遍历: ";
tree->postOrder();
cout << endl;

cout << "== 最小值: " << tree->minimum() << endl;
cout << "== 最大值: " << tree->maximum() << endl;
cout << "== 树的详细信息: " << endl;
tree->print();

// 设置check_remove=1,测试"删除函数"
if(check_remove)
{
for(i=0; i<ilen; i++)
{
tree->remove(a[i]);

cout << "== 删除节点: " << a[i] << endl;
cout << "== 树的详细信息: " << endl;
tree->print();
cout << endl;
}
}

// 销毁红黑树
tree->destroy();

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: