5.18红黑树

红黑树实现代码

#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;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值