红黑树实现代码
#include<utility>
template<class K,class V>
struct RBNdoe
{
typedef bool color;
RBNode<K, V>* _parent;
RBNode<K, V>* _left;
RBNode<K, V>* _right;
pair<K, V> _kv;
COLOR _color;
RBNode(const pair<K, V>& KV = pair<K, V>())
:_parent(nullptr)
,_left(nullptr)
,_right(nullptr)
,_kv(kv)
,_color(RED)
{}
};
template<class K, class V>
class RBTree
{
public:
typedf RBNdoe<K, V> Node;
RBTree()
:_header(new Node)
{
//创建空树
_header->left = _header->right = _header;
}
bool insert(const pair<K, V>& kv)
{
//1.搜索树的插入
//空树:_header->parent:nullptr
if (_header->parent == nullptr)
{
//创建根节点
Node* root = new Node(kv);
_header->parent = root;
root->parent = header;
_header->_left = _header->_right = root;
//根节点是黑色
root->color = BLACK;
return true;
}
//从根节点开始搜索
Node* cur = _header->parent;
Node* parent = nullptr;
while(cur)
{
parent = cur;
//和key值进行比较
//kv:pair<k,v>key:pair.first
if (cur->kv.first == kv.first)
{
//key值不允许重复
return false;
}
else if (cur->_kv.first->kv.first)
{
cur = cur->left;
}
else
{
cur = cur->right;
}
}
//创建待插入的节点
cur = new Node(kv);
if (parent->kv.first > cur->_kv.first)
parent->_left = cur;
else
parent->_right = cur;
cur->_parent = parent;
//2.修改颜色或者调整结构
//判断是否有红色连续的节点
while (cur != _header->_parent&&cur->p_parent->color == RED)
{
parent = cur->_parent;
Node* gfather = parent->_parent;
if (gfather->_left == parent)
{
Node* cunle = gfather->_right;
//1.uncle存在的,并且是红色的
if (uncle && uncle->_color == RED)
{
parent->_color = uncle->_color = BLACK;
gfather->_color = RED;
cur = gfather;
}
}
else
{
}
}
//根节点的颜色改成黑色
_header->_parent->color = BLACK;
//更新header的左右指向
_header
if(pParent== grandFather->_pRight)
{
PNode unclue = grandFather->_pRight;