用红黑树实现map和set
上一篇文章讲解了如何实现红黑树:
https://blog.csdn.net/Radium_1209/article/details/104873813
这里我们用已经实现的红黑树来写一个简单的map和set。
因为map有两个参数,所以我们要先对原来的代码进行微调,将传入的参数调整为Key和Value。
还有一些地方需要微调,详见https://github.com/Radium1209/Red-Black-Tree
红黑树的接口定义
#ifndef RED_BLACK_TREE
#define RED_BALCK_TREE
#include <stdlib.h>
/* 红黑树颜色 */
enum RBTColor
{
RED,
BLACK,
};
/* 红黑树节点 */
template<class Key, class Value>
class RBTNode
{
public:
RBTNode( RBTColor col, Key k, Value val, RBTNode* lch, RBTNode* rch, RBTNode* fa )
: color( col ), key( k ), value( val ), blackNum( 0 ), leftChild( lch ), rightChild( rch ), father( fa ) {
}
RBTColor color; // 颜色(红或黑)
Key key; // 关键字
Value value; // 数据
int blackNum; // 该节点的路径包含的黑色节点个数
RBTNode *leftChild; // 左孩子
RBTNode *rightChild; // 右孩子
RBTNode *father; // 父节点
};
/* 节点-层数对,用于遍历 */
template<class Key, class Value>
class NLPair
{
public:
NLPair( RBTNode<Key, Value>* node, int layer )
: node( node ), layer( layer ) {
}
RBTNode<Key, Value>* node;
unsigned int layer;
};
template<class Key, class Value>
class RBTree
{
private:
RBTNode<Key, Value> *root;
public:
RBTree();
~RBTree();
// 判断是否为红黑树
bool isRBT();
// 各种插入函数
void insert( Key key );
void insert( Key key, Value value );
void insertUnique( Key key );
void insertUnique( Key key, Value value );
// 删除函数
void erase( Key key );
// 清空
void clear();
// 查询函数
RBTNode<Key, Value>* find( Key key );
// 画红黑树,测试用
void draw();
// 求开始结束节点,此处没有实现iterator,所以用处不大
RBTNode<Key, Value>* begin();
RBTNode<Key, Value>* end();
// 求节点个数和是否为空
unsigned int size();
bool empty();
// 一些内部函数
private:
bool isBST( RBTNode<Key, Value> *node );
bool hasTwoRed( RBTNode<Key, Value>