用红黑树实现map和set

用红黑树实现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> 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值