【C++】红黑树

红黑树的概念

红黑树,是一种二叉搜索树,但在每个结点上增加一个存储位表示结点的颜色,可以是Red或
Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制,红黑树确保没有一条路
径会比其他路径长出俩倍,因而是接近平衡的。

在这里插入图片描述

红黑树的性质

  1. 每个结点不是红色就是黑色
  2. 根节点是黑色的
  3. 如果一个节点是红色的,则它的两个孩子结点是黑色的
  4. 对于每个结点,从该结点到其所有后代叶结点的简单路径上,均 包含相同数目的黑色结点
  5. 每个叶子结点都是黑色的(此处的叶子结点指的是空结点)

红黑树的节点定义

    enum class Colour : unsigned int//class是用来限制类型的
	{
		RED,
		BLACK
	};

	template<class T>
	struct RBTreeNode
	{
		RBTreeNode<T>* _left;
		RBTreeNode<T>* _right;
		RBTreeNode<T>* _parent;
		T _data;
		Colour _col;

		RBTreeNode(const T& data)
			:_left(nullptr)
			, _right(nullptr)
			, _parent(nullptr)
			, _data(data)
			, _col(Colour::RED)
		{}
	};

这里是将眼色默认设定成为红色,原因是在上述写的红黑树的性质中有两条的内容是这样写的,不能连续出现红节点,和每条路径下的黑节点数量必须相同。在两者必须要违反一种的情况下选择了前者。前者的代价要比后者的代价小得多。

红黑树的结构

为了后续实现关联式容器简单,红黑树的实现中增加一个头结点,因为跟节点必须为黑色,为了
与根节点进行区分,将头结点给成黑色,并且让头结点的 pParent 域指向红黑树的根节点,pLeft
域指向红黑树中最小的节点,_pRight域指向红黑树中最大的节点,如下:
在这里插入图片描述
上述的结构式STL源码当中的结构,而我接下来要写的不是上述的结构。

红黑树的插入操作

红黑树是在二叉搜索树的基础上加上其平衡限制条件,因此红黑树的插入可分为两步:
1. 按照二叉搜索的树规则插入新节点

if (_root == nullptr)
{
	_root = new Node(data);
	_root->_col = Colour::BLACK;
	return make_pair(itertor(_root), true);
}

Node* parent = nullptr;
Node* cur = _root;
KeyofValue kov;
while (cur)
{
	if (kov(cur->_data) < kov(data))
	{
		parent = cur;
		cur = cur->_right;
	}
	else if (kov(cur->_data) > kov(data))
	{
		parent = cur;
		cur = cur->_left;
	}
	else
	{
		return make_pair(itertor(cur), false);
	}
}

cur = new Node(data);
Node* newnode = cur;
if (kov(parent->_data) > kov(data))
{
	parent->_left = cur;
}
else
{
	parent->_right = cur;
}
cur->_parent = parent;

上面的代码是第一步,为了找到插入节点属于他的位置。就是二叉搜索树的结构。

2、检测新节点插入后,红黑树的性质是否造到破坏

while (parent && parent->_col == Colour::RED)
{
	Node* grandfather = parent->_parent;
	if (parent == grandfather->_left)
	{
		Node* uncle = grandfather->_right;
		if (uncle && uncle->_col == Colour::RED)
		{
			// 情况1:u存在且为红,变色处理,并继续往上处理
			parent->_col = Colour::BLACK;
			uncle->_col = Colour::BLACK;
			grandfather->_col = Colour::RED;

			cur = grandfather;
			parent = cur->_parent;
		}
		else
		{
			// 情况2+3:u不存在/u存在且为黑,旋转+变色
			//    g
			//  p   u
			// c
			if (cur == parent->_left)
			{
				RotateR(grandfather);
				parent->_col = Colour::BLACK;
				grandfather->_col = Colour::RED;
			}
			else
			{
				//    g
				//  p   u
				//    c
				RotateL(parent);
				RotateR(grandfather);

				cur->_col = Colour::BLACK;
				grandfather->_col = Colour::RED;
			}
			break;//旋转了就可以退出了
		}

	}
	else // (grandfather->_right == parent)
	{
		//    g
		//  u   p
		//        c
		Node* uncle = grandfather->_left;
		// 情况1:u存在且为红,变色处理,并继续往上处理
		if (uncle && uncle->_col == Colour::RED)
		{
			parent->_col = Colour::BLACK;
			uncle->_col = Colour::BLACK;
			grandfather->_col = Colour::RED;

			// 继续往上调整
			cur = grandfather;
			parent = cur->_parent;
		}
		else // 情况2+3:u不存在/u存在且为黑,旋转+变色
		{
			//    g
			//  u   p
			//        c
			if (cur == parent->_right)
			{
				RotateL(grandfather);
				grandfather->_col = Colour::RED;
				parent->_col = Colour::BLACK;
			}
			else
			{
				//    g
				//  u   p
				//    c
				RotateR(parent);
				RotateL(grandfather);
				cur->_col = Colour::BLACK;
				grandfather->_col = Colour::RED;
			}

			break;
		}
	}
}

_root->_col = Colour::BLACK;

return make_pair(itertor(newnode), true);

因为新节点的默认颜色是红色,因此:如果其双亲节点的颜色是黑色,没有违反红黑树任何
性质,则不需要调整;但当新插入节点的双亲节点颜色为红色时,就违反了性质三不能有连
在一起的红色节点,此时需要对红黑树分情况来讨论:
约定:cur为当前节点,p为父节点,g为祖父节点,u为叔叔节点

  • 情况一: cur为红,p为红,g为黑,u存在且为红
    在这里插入图片描述
    在这里插入图片描述
    cur和p均为红,违反了性质三,此处能否将p直接改为黑?
    解决方式:将p,u改为黑,g改为红,然后把g当成cur,继续向上调整。
  • 情况二: cur为红,p为红,g为黑,u不存在/u存在且为黑
    在这里插入图片描述
    在这里插入图片描述
    p为g的左孩子,cur为p的左孩子,则进行右单旋转;相反,
    p为g的右孩子,cur为p的右孩子,则进行左单旋转
    p、g变色–p变黑,g变红
  • 情况三: cur为红,p为红,g为黑,u不存在/u存在且为黑
    在这里插入图片描述

红黑树的验证

红黑树的检测分为两步:

    1. 检测其是否满足二叉搜索树(中序遍历是否为有序序列)
    1. 检测其是否满足红黑树的性质
bool IsBalance()
		{
			if (_root && _root->_col == Colour::RED)
			{
				cout << "根节点颜色是红色" << endl;
				return false;
			}

			int benchmark = 0;
			Node* cur = _root;
			while (cur)
			{
				if (cur->_col == Colour::BLACK)
					++benchmark;
				cur = cur->_left;
			}

			// 连续红色节点
			return _Check(_root, 0, benchmark);
		}
bool _Check(Node* root, int blackNum, int benchmark)
{
	if (root == nullptr)
	{
		if (benchmark != blackNum)
		{
			cout << "某条路径黑色节点的数量不相等" << endl;
			return false;
		}

		return true;
	}

	if (root->_col == Colour::BLACK)
	{
		++blackNum;
	}

	if (root->_col == Colour::RED
		&& root->_parent
		&& root->_parent->_col == Colour::RED)
	{
		cout << "存在连续的红色节点" << endl;
		return false;
	}

	return _Check(root->_left, blackNum, benchmark)
		&& _Check(root->_right, blackNum, benchmark);
}

红黑树删除

传送门

红黑树模拟实现STL中的map与set

begin()与end()
STL明确规定,begin()与end()代表的是一段前闭后开的区间,而对红黑树进行中序遍历后,
可以得到一个有序的序列,因此:begin()可以放在红黑树中最小节点(即最左侧节点)的位
置,end()放在最大节点(最右侧节点)的下一个位置,关键是最大节点的下一个位置在哪块?
能否给成nullptr呢?答案是行不通的,因为对end()位置的迭代器进行–操作,必须要能找最
后一个元素,此处就不行,因此最好的方式是将end()放在头结点的位置:

  • operator++()与operator–()
// 找迭代器的下一个节点,下一个节点肯定比其大
void Increasement()
{
    //分两种情况讨论:_pNode的右子树存在和不存在
    // 右子树存在
 if(_pNode->_pRight)
 {
         // 右子树中最小的节点,即右子树中最左侧节点
 _pNode = _pNode->_pRight;
 while(_pNode->_pLeft)
 _pNode = _pNode->_pLeft;
 }
 else
 {
         // 右子树不存在,向上查找,直到_pNode != pParent->right
 PNode pParent = _pNode->_pParent;
 while(pParent->_pRight == _pNode)
 {
 _pNode = pParent;
 pParent = _pNode->_pParent;
 }
 // 特殊情况:根节点没有右子树
 if(_pNode->_pRight != pParent)
 _pNode = pParent;
 }
}
// 获取迭代器指向节点的前一个节点
void Decreasement()
{
     //分三种情况讨论:_pNode 在head的位置,_pNode 左子树存在,_pNode 左子树不
存在
     // 1. _pNode 在head的位置,--应该将_pNode放在红黑树中最大节点的位置
 if(_pNode->_pParent->_pParent == _pNode && _pNode->_color == RED)
 _pNode = _pNode->_pRight;
 else if(_pNode->_pLeft)
 {
        // 2. _pNode的左子树存在,在左子树中找最大的节点,即左子树中最右侧节点
 _pNode = _pNode->_pLeft;
 while(_pNode->_pRight)
 _pNode = _pNode->_pRight;
 }
 else
 {
         // _pNode的左子树不存在,只能向上找
 PNode pParent = _pNode->_pParent;
 while(_pNode == pParent->_pLeft)
 {
 _pNode = pParent;
 pParent = _pNode->_pParent;
 }
 _pNode = pParent;
 }
}

改造红黑树

// 因为关联式容器中存储的是<key, value>的键值对,因此
// k为key的类型,
// ValueType: 如果是map,则为pair<K, V>; 如果是set,则为k
// KeyOfValue: 通过value来获取key的一个仿函数类
template<class K, class ValueType, class KeyOfValue>
class RBTree
{
 typedef RBTreeNode<ValueType> Node;
 typedef Node* PNode;
public:
 typedef RBTreeIterator<ValueType, ValueType*, ValueType&> Iterator;
public:
  RBTree();
 ~RBTree()
 /
 // Iterator
 Iterator Begin(){ return Iterator(_pHead->_pLeft);}
 Iterator End(){ return Iterator(_pHead);}
 //
 // Modify
 pair<Iterator, bool> Insert(const ValueType& data)
 {
      // 插入节点并进行调整
      // 参考上文...
 return make_pair(Iterator(pNewNode), true);
 }
 // 将红黑树中的节点清空
 void Clear();
 Iterator Find(const K& key);
 //
 // capacity
 size_t Size()const;
 bool Empty()const;
  // ……
private:
 PNode _pHead;
 size_t _size;  // 红黑树中有效节点的个数
};

map的模拟实现

template<class K, class V>
 class map
 {
 typedef pair<K, V> ValueType;
      // 作用:将value中的key提取出来
 struct KeyOfValue
 {
 const K& operator()(const ValueType& v)
 { return v.first;}
 };
 typedef RBTree<K, ValueType, KeyOfValue> RBTree;
 public:
 typedef typename RBTree::Iterator iterator;
 public:
 map(){}
 /
 // Iterator
 iterator begin(){ return _t.Begin();}
 iterator end(){ return _t.End();}
 /
 // Capacity
 size_t size()const{ return _t.Size();}
 bool empty()const{ return _t.Empty();}
比特就业课
4.3.4 set的模拟实现
set的底层为红黑树,因此只需在set内部封装一棵红黑树,即可将该容器实现出来(具体实现可参
考map)/
 // Acess
 V& operator[](const K& key)
 { return (*(_t.Insert(ValueType(key, V()))).first).second;}
 const V& operator[](const K& key)const;
 
 // modify
 pair<iterator, bool> insert(const ValueType& data) { return
_t.Insert(data);}
 void clear(){ _t.Clear();}
 iterator find(const K& key){ return _t.Find(key);}
 private:
 RBTree _t;
 };

set的模拟实现

template<class K>
 class set
 {
 typedef K ValueType;
 // 作用是:将value中的key提取出来
 struct KeyOfValue
 {
 const K& operator()(const ValueType& key)
 { return key;}
 };
      // 红黑树类型重命名
 typedef RBTree<K, ValueType, KeyOfValue> RBTree;
 public:
 typedef typename RBTree::Iterator iterator;
 public:
 Set(){}
 /
 // Iterator
 iterator Begin();
 iterator End();
 /
 // Capacity
 size_t size()const;
 bool empty()const;
 
 // modify
 pair<iterator, bool> insert(const ValueType& data)
 {
 return _t.Insert(data);
 }
 void clear();
 iterator find(const K& key);
 private:
 RBTree _t;
 };
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值