• C++模拟实现红黑树


    前言

    有了AVL树,为什么还要用红黑树?

    红黑树和AVL树都是高效的平衡二叉树,增删改查的时间复杂度都是 O ( l o g 2 n ) O(log_2 n ) O(log2n)红黑树不追求绝对平衡,其只需保证最长路径不超过最短路径的2倍,相对而言,降低了插入和旋转的次数,所以在经常进行增删的结构中性能比AVL树更优,而且红黑树实现比较简单,所以实际运用中红黑树更多

    一、什么是红黑树

    红黑树(Red Black Tree) 是一种自平衡二叉查找树,是在计算机科学中用到的一种数据结构,典型的用途是实现关联数组。红黑树是在1972年由Rudolf Bayer发明的,当时被称为平衡二叉B树(symmetric binary B-trees)。后来,在1978年被 Leo J. Guibas 和 Robert Sedgewick 修改为如今的 “红黑树”。红黑树是一种特化的AVL树(平衡二叉树),都是在进行插入和删除操作时通过特定操作保持二叉查找树的平衡,从而获得较高的查找性能。 它虽然是复杂的,但它的最坏情况运行时间也是非常良好的,并且在实践中是高效的: 它可以在 O ( l o g 2 n ) O(log_2 n) O(log2n)时间内做查找,插入和删除,这里的 n 是树中元素的数目

    二、红黑树的性质

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

    性质如下:

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

    【注意】
    红黑树中最短的路径即是全黑节点的路径,最长的路径则是一黑一红间隔的路径,因此红黑树就保证了:其最长路径中节点个数不会超过最短路径节点个数的两倍。

    三、红黑树节点定义

    红黑树的节点与AVL树几乎相同,只是红黑树节点相当于AVL树来说新增了颜色这个成员变量,而少了平衡因子。

    
    enum Colour
    {
    	RED,
    	BLACK,
    };
    
    template<class K, class V>
    struct RBTreeNode
    {
    	RBTreeNode<K, V>* _left;
    	RBTreeNode<K, V>* _right;
    	RBTreeNode<K, V>* _parent;
    	pair<K, V> _kv;
    
    	Colour _col;
    
    	RBTreeNode(const pair<K, V>& kv)
    		:_kv(kv)
    		, _left(nullptr)
    		, _right(nullptr)
    		, _parent(nullptr)
    		, _col(RED)
    	{}
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    四、红黑树的插入操作

    红黑树是在二叉搜索树的基础上进行插入并加上其平衡限制条件。由于上述性质的约束:插入的新节点不能为黑节点,应插入红节点。因为当插入黑节点时将破坏性质5,所以每次插入的点都是红结点,但是若他的父节点也为红,那岂不是破坏了性质4?所以要做一些“旋转”和一些节点的变色!以下是红黑树插入过程中所遇到的所有情况。
    注意:这里约定cur为当前节点,p为父节点,u为叔叔节点,g为祖父节点。

    情况一

    情况一:即cur为红,p为红,g为黑,u存在且为红。


    调整方法,u节点存在且为红色,将p和u改成黑色,g改成红色,如果g不是根,则g一定有父节点,且g的双亲如果是红色,则需要继续往上调整,即g变成cur,继续直到满足红黑树条件或者到达根节点,最后将根节点置为黑色即可。

    情况二

    情况二:即cur为红,p为红,g为黑,u不存在 / u为黑。
    【说明】
    u的情况有两种:

    1. 如果u节点不存在,则cur一定是新插入的节点,因为如果cur不是新插入的节点,则cur和p一定有一个节点的颜色是黑色的,就不满足性质4:每条路径黑色节点的个数相同。
    2. 如果节点u存在,则其一定是黑色的。那么cur节点原来一定是黑色的,即当前cur节点是红色的原因是因为cur的子树在调整过程中将cur节点的颜色有黑色变为红色

      p为g的左孩子,cur为p的左孩子,则进行右单旋转;相反,p为g的右孩子,cur为p的右孩子,则进行左单旋转。

    情况三

    情况三: 即cur为红,p为红,g为黑,u不存在 / u为黑。

    p为g的左孩子,cur为p的右孩子,则针对p做左单旋转;相反,p为g的右孩子,cur为p的左孩子,则针对p做右单旋转,就变成了情况二,在右旋或者左旋加变色即可。

    五、红黑树的验证

    红黑树的检测分为两步:

    1. 检测其是否满足二叉搜索树(中序遍历是否为有序序列)
    2. 检测其是否满足红黑树的性质

    代码如下:

    bool IsBalanceRBTree()
    {
    	if (_root == nullptr) //空树是红黑树
    		return true;
    
    	// 检查根节点是否是红黑树
    	if (BLACK != _root->_col)
    	{
    		cout << "违反红黑树性质二:根节点必须是黑色" << endl;
    		return false;
    	}
    
    	//获取任意一条路径中的黑色结点个数——比较基准值
    	size_t blackCount = 0;
    	Node* cur = _root;
    	while (cur)
    	{
    		if (BLACK == cur->_col)
    		{
    			++blackCount;
    		}
    		cur = cur->_left;
    	}
    
    	//检测是否满足红黑树的性质,k用来记录路径中黑色节点的个数
    	size_t k = 0;
    	return _IsValidRBTree(_root, k, blackCount);	
    }
    
    bool _IsValidRBTree(Node* root, size_t k, const size_t& blackCount)
    {
    	//走到空, 判断 k 和 blackCount是否相等
    	if (nullptr == root)
    	{
    		if (k != blackCount)
    		{
    			cout << "违反性质四:每条路径中黑色节点个数必须相等" << endl;
    			return false;
    		}
    		return true;
    	}
    	// 统计黑色节点的个数
    	if (BLACK == root->_col)
    		++k;
    
    	//检查当前节点与其双亲节点是否都为红色
    	if (RED == root->_col && root->_parent && RED == root->_parent->_col)
    	{
    		cout << "违反性质三:存在连在一起的红色节点" << endl;
    		return false;
    	}
    
    	return _IsValidRBTree(root->_left, k, blackCount) && _IsValidRBTree(root->_right, k, blackCount);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    六、红黑树完整代码

    #pragma once
    #include
    #include
    #include
    #include
    using namespace std;
    
    enum Colour
    {
    	RED,
    	BLACK,
    };
    
    template<class K, class V>
    struct RBTreeNode
    {
    	RBTreeNode<K, V>* _left;
    	RBTreeNode<K, V>* _right;
    	RBTreeNode<K, V>* _parent;
    	pair<K, V> _kv;
    
    	Colour _col;
    
    	RBTreeNode(const pair<K, V>& kv)
    		:_kv(kv)
    		, _left(nullptr)
    		, _right(nullptr)
    		, _parent(nullptr)
    		, _col(RED)
    	{}
    };
    
    template<class K, class V>
    class RBTree
    {
    	typedef RBTreeNode<K, V> Node;
    public:
    	bool Insert(const pair<K, V>& kv)
    	{
    		// 1、搜索树的插入规则
    		// 2、看是否违反平衡规则
    		if (_root == nullptr)
    		{
    			_root = new Node(kv);
    			_root->_col = BLACK;
    			return true;
    		}
    
    		Node* parent = nullptr;
    		Node* cur = _root;
    		while (cur)
    		{
    			if (cur->_kv.first < kv.first)
    			{
    				parent = cur;
    				cur = cur->_right;
    			}
    			else if (cur->_kv.first > kv.first)
    			{
    				parent = cur;
    				cur = cur->_left;
    			}
    			else
    			{
    				return false;
    			}
    		}
    
    		//找到了插入位置
    		cur = new Node(kv);
    		cur->_col = RED; //插入结点为红色
    		if (parent->_kv.first < kv.first)
    		{
    			parent->_right = cur;
    		}
    		else
    		{
    			parent->_left = cur;
    		}
    		cur->_parent = parent;
    
    
    		//存在连续的红结点
    		while (parent && parent->_col == RED)
    		{
    			Node* grandfather = parent->_parent;
    			assert(grandfather);
    
    			//parent在左
    			if (grandfather->_left == parent)
    			{
    				Node* uncle = grandfather->_right;
    				//情况一
    				if (uncle && uncle->_col == RED) //叔叔存在且为红色
    				{
    					//变色
    					parent->_col = uncle->_col = BLACK;
    					grandfather->_col = RED;
    
    					//继续往上处理
    
    					cur = grandfather;
    					parent = cur->_parent;
    				}
    				else // 叔叔 不存在 或者 存在且为黑
    				{
    					//情况二
    					if (cur == parent->_left) //右单旋
    					{
    						//    g
    						//  p
    						//c
    						RotateR(grandfather);
    						parent->_col = BLACK;
    						grandfather->_col = RED;
    
    					}
    					//情况三
    					else //左右双旋
    					{
    						//    g
    						//  p
    						//    c
    
    						RotateL(parent);
    						RotateR(grandfather);
    						
    						cur->_col = BLACK;
    						grandfather->_col = RED;
    					}
    					break;
    				}
    			}
    			//parent在右
    			else  //(grandfather->_right == parent)
    			{
    				Node* uncle = grandfather->_left;
    				//情况一
    				if (uncle && uncle->_col == RED) //叔叔存在且为红色
    				{
    					//变色
    					parent->_col = uncle->_col = BLACK;
    					grandfather->_col = RED;
    
    					//继续往上处理
    
    					cur = grandfather;
    					parent = cur->_parent;
    				}
    				else // 叔叔 不存在 或者 存在且为黑
    				{
    					//情况二
    					if (cur == parent->_right) //左单旋
    					{
    						// g
    						//   p
    						//     c
    						RotateL(grandfather);
    
    						parent->_col = BLACK;
    						grandfather->_col = RED;
    					}
    					//情况三
    					else //(cur == parent->_left) 右左双旋
    					{
    						// g
    						//   p
    						// c
    						RotateR(parent);
    						RotateL(grandfather);
    
    						cur->_col = BLACK;
    						grandfather->_col = RED;
    					}
    					break;
    				}
    			}
    		}
    		_root->_col = BLACK;
    		return true;
    	}
    
    	void InOrder()
    	{
    		_InOrder(_root);
    		cout << endl;
    	}
    
    	void Height()
    	{
    		cout << "最长路径:" << _maxHeight(_root) << endl;
    		cout << "最短路径:" << _minHeight(_root) << endl;
    	}
    
    	vector<vector<int>> levelOrder() {
    		vector<vector<int>> vv;
    		if (_root == nullptr)
    			return vv;
    
    		queue<Node*> q;
    		int levelSize = 1;
    		q.push(_root);
    
    		while (!q.empty())
    		{
    			// levelSize控制一层一层出
    			vector<int> levelV;
    			while (levelSize--)
    			{
    				Node* front = q.front();
    				q.pop();
    				levelV.push_back(front->_kv.first);
    				if (front->_left)
    					q.push(front->_left);
    
    				if (front->_right)
    					q.push(front->_right);
    			}
    			vv.push_back(levelV);
    			for (auto e : levelV)
    			{
    				cout << e << " ";
    			}
    			cout << endl;
    
    			// 上一层出完,下一层就都进队列
    			levelSize = q.size();
    		}
    
    		return vv;
    	}
    
    	//检查是否是红黑树
    	bool IsBalanceRBTree()
    	{
    		if (_root == nullptr) //空树是红黑树
    			return true;
    
    		// 检查根节点是否是红黑树
    		if (BLACK != _root->_col)
    		{
    			cout << "违反红黑树性质二:根节点必须是黑色" << endl;
    			return false;
    		}
    
    		//获取任意一条路径中的黑色结点个数——比较基准值
    		size_t blackCount = 0;
    		Node* cur = _root;
    		while (cur)
    		{
    			if (BLACK == cur->_col)
    			{
    				++blackCount;
    			}
    			cur = cur->_left;
    		}
    
    		//检测是否满足红黑树的性质,k用来记录路径中黑色节点的个数
    		size_t k = 0;
    		return _IsValidRBTree(_root, k, blackCount);	
    	}
    
    private:
    	void RotateL(Node* parent)
    	{
    		Node* subR = parent->_right;
    		Node* subRL = subR->_left;
    
    		parent->_right = subRL;
    		if (subRL)
    			subRL->_parent = parent;
    
    		Node* grandParent = parent->_parent;
    		subR->_left = parent;
    		parent->_parent = subR;
    
    		if (parent == _root)
    		{
    			_root = subR;
    			subR->_parent = nullptr;
    		}
    		else
    		{
    			if (parent == grandParent->_left)
    			{
    				grandParent->_left = subR;
    			}
    			else
    			{
    				grandParent->_right = subR;
    			}
    			subR->_parent = grandParent;
    		}
    	}
    
    	void RotateR(Node* parent)
    	{
    		Node* subL = parent->_left;
    		Node* subLR = subL->_right;
    
    		parent->_left = subLR;
    		if (subLR)
    			subLR->_parent = parent;
    
    		Node* grandParent = parent->_parent;
    		subL->_right = parent;
    		parent->_parent = subL;
    
    		if (parent == _root)
    		{
    			_root = subL;
    			subL->_parent = nullptr;
    		}
    		else
    		{
    			if (parent == grandParent->_left)
    			{
    				grandParent->_left = subL;
    			}
    			else
    			{
    				grandParent->_right = subL;
    			}
    			subL->_parent = grandParent;
    		}
    	}
    
    	void _InOrder(Node* root)
    	{
    		if (root == nullptr)
    			return;
    
    		_InOrder(root->_left);
    		cout << root->_kv.first << " ";
    		_InOrder(root->_right);
    	}
    
    	int _maxHeight(Node* root)
    	{
    		if (root == nullptr)
    			return 0;
    
    		int lh = _maxHeight(root->_left);
    		int rh = _maxHeight(root->_right);
    
    		return lh > rh ? lh + 1 : rh + 1;
    	}
    
    	int _minHeight(Node* root)
    	{
    		if (root == nullptr)
    			return 0;
    
    		int lh = _minHeight(root->_left);
    		int rh = _minHeight(root->_right);
    
    		return lh < rh ? lh + 1 : rh + 1;
    	}
    
    	bool _IsValidRBTree(Node* root, size_t k, const size_t& blackCount)
    	{
    		//走到空, 判断 k 和 blackCount是否相等
    		if (nullptr == root)
    		{
    			if (k != blackCount)
    			{
    				cout << "违反性质四:每条路径中黑色节点个数必须相等" << endl;
    				return false;
    			}
    			return true;
    		}
    		// 统计黑色节点的个数
    		if (BLACK == root->_col)
    			++k;
    
    		//检查当前节点与其双亲节点是否都为红色
    		if (RED == root->_col && root->_parent && RED == root->_parent->_col)
    		{
    			cout << "违反性质三:存在连在一起的红色节点" << endl;
    			return false;
    		}
    
    		return _IsValidRBTree(root->_left, k, blackCount) && _IsValidRBTree(root->_right, k, blackCount);
    	}
    
    private:
    	Node* _root = nullptr;
    };
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390

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

    1. 红黑树的迭代器实现

    迭代器的好处是可以方便遍历,是数据结构的底层实现与用户透明。如果想要给红黑树增加迭代
    器,需要考虑以前问题:
    STL明确规定,begin()与end()代表的是一段前闭后开的区间,而对红黑树进行中序遍历后,可以得到一个有序的序列,因此:begin()可以放在红黑树中最小节点(即最左侧节点)的位置,end()放在最大节点(最右侧节点)的下一个位置,关键是最大节点的下一个位置在哪块?
    STL库中的红黑树实现带了一个哨兵位的头节点,通过头节点存储begin和end的指针即解决了这个问题。由于为了减少操作,上面所实现的红黑树没有带头节点,因此只需要begin()放在红黑树中最小节点(即最左侧节点)的位置,end()直接指向nullptr。

    红黑树迭代器实现代码:

    template<class T, class Ref, class Ptr>
    struct __RBTreeIterator
    {
    	typedef RBTreeNode<T> Node;
    
    	typedef __RBTreeIterator<T, Ref, Ptr> self;
    	Node* _node;
    
    	__RBTreeIterator(Node* node)
    		:_node(node)
    	{}
    
    	Ref operator*()
    	{
    		return _node->_data;
    	}
    
    	Ptr operator->()
    	{
    		return &_node->_data;
    	}
    
    	self& operator++()
    	{
    		if (_node->_right == nullptr)
    		{
    			//找祖先里面,孩子是父亲左的那个
    			Node* cur = _node;
    			Node* parent = cur->_parent;
    			while (parent && parent->_right == cur)
    			{
    				cur = cur->_parent;
    				parent = cur->_parent;
    			}
    			_node = parent;
    		}
    		else
    		{
    			//右子树的最左节点
    			Node* subL = _node->_right;
    			while (subL->_left)
    			{
    				subL = subL->_left;
    			}
    			_node = subL;
    		}
    
    		return *this;
    	}
    
    	self operator++(int)
    	{
    		self tmp(*this);
    		++(*this);
    		return tmp;
    	}
    
    	self& operator--()
    	{
    		if (_node->_left == nullptr)
    		{
    			//找祖先里面,找祖先里面,孩子是父亲右的那个
    			Node* cur = _node;
    			Node* parent = cur->_parent;
    			while (parent && parent->_left)
    			{
    				cur = cur->_parent;
    				parent = cur->_parent;
    			}
    			_node = parent;
    		}
    		else
    		{
    			//左子树的最右节点
    			Node* subR = _node->_left;
    			while (subR->_right)
    			{
    				subR = subR->_left;
    			}
    			_node = subR;
    		}
    		return *this;
    	}
    
    	self operator--(int)
    	{
    		self tmp(*this);
    		--(*this);
    		return tmp;
    	}
    
    	bool operator!=(const self& s)
    	{
    		return _node != s._node;
    	}
    
    	bool operator==(const self& s)
    	{
    		return _node == s._node;
    	}
    
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102

    2. 改造红黑树

    • 因为关联式容器中存储的是的键值对,因此 k为key的类型,ValueType: 如果是map,则为pair; 如果是set,则为k。
    • KeyOfValue: 通过value来获取key的一个仿函数类

    红黑树改造:

    // T决定红黑树存什么数据
    // set  RBTree
    // map  RBTree>
    // KeyOfT -> 支持取出T对象中key的仿函数
    template<class K, class T, class KeyOfT>
    class RBTree
    {
    	typedef RBTreeNode<T> Node;
    public:
    
    	typedef __RBTreeIterator<T, T&, T*> iterator;
    	typedef __RBTreeIterator<T, const T&, const T*> const_iterator;
    
    	iterator Begin()
    	{
    		Node* subL = _root;
    		while (subL && subL->_left)
    		{
    			subL = subL->_left;
    		}
    		return subL;
    	}
    
    	iterator End()
    	{
    		return iterator(nullptr);
    	}
    
    	const_iterator Begin() const
    	{
    		Node* subL = _root;
    		while (subL && subL->_left)
    		{
    			subL = subL->_left;
    		}
    		return subL;
    	}
    
    	const_iterator End() const
    	{
    		return const_iterator(nullptr);
    	}
    
    	pair<iterator,bool> Insert(const T& data)
    	{
    		// 1、搜索树的插入规则
    		// 2、看是否违反平衡规则
    		if (_root == nullptr)
    		{
    			_root = new Node(data);
    			_root->_col = BLACK;
    		    return make_pair(iterator(_root), true);
    
    		}
    
    		KeyOfT kot;
    
    		Node* parent = nullptr;
    		Node* cur = _root;
    		while (cur)
    		{
    			if (kot(cur->_data) < kot(data))
    			{
    				parent = cur;
    				cur = cur->_right;
    			}
    			else if (kot(cur->_data) > kot(data))
    			{
    				parent = cur;
    				cur = cur->_left;
    			}
    			else
    			{
    				return make_pair(iterator(cur), true);
    			}
    		}
    
    		//找到了插入位置
    		cur = new Node(data);
    		Node* newnode = cur;
    		cur->_col = RED; //插入结点为红色
    		if (kot(parent->_data) < kot(data))
    		{
    			parent->_right = cur;
    		}
    		else
    		{
    			parent->_left = cur;
    		}
    		cur->_parent = parent;
    
    
    		//存在连续的红结点
    		while (parent && parent->_col == RED)
    		{
    			Node* grandfather = parent->_parent;
    			//assert(grandfather);
    
    			//parent在左
    			if (grandfather->_left == parent)
    			{
    				Node* uncle = grandfather->_right;
    				//情况一
    				if (uncle && uncle->_col == RED) //叔叔存在且为红色
    				{
    					//变色
    					parent->_col = uncle->_col = BLACK;
    					grandfather->_col = RED;
    
    					//继续往上处理
    
    					cur = grandfather;
    					parent = cur->_parent;
    				}
    				else // 叔叔 不存在 或者 存在且为黑
    				{
    					//情况二
    					if (cur == parent->_left) //右单旋
    					{
    						//    g
    						//  p
    						//c
    						RotateR(grandfather);
    						parent->_col = BLACK;
    						grandfather->_col = RED;
    
    					}
    					//情况三
    					else //左右双旋
    					{
    						//    g
    						//  p
    						//    c
    
    						RotateL(parent);
    						RotateR(grandfather);
    						
    						cur->_col = BLACK;
    						grandfather->_col = RED;
    					}
    					break;
    				}
    			}
    			//parent在右
    			else  //(grandfather->_right == parent)
    			{
    				Node* uncle = grandfather->_left;
    				//情况一
    				if (uncle && uncle->_col == RED) //叔叔存在且为红色
    				{
    					//变色
    					parent->_col = uncle->_col = BLACK;
    					grandfather->_col = RED;
    
    					//继续往上处理
    
    					cur = grandfather;
    					parent = cur->_parent;
    				}
    				else // 叔叔 不存在 或者 存在且为黑
    				{
    					//情况二
    					if (cur == parent->_right) //左单旋
    					{
    						// g
    						//   p
    						//     c
    						RotateL(grandfather);
    
    						parent->_col = BLACK;
    						grandfather->_col = RED;
    					}
    					//情况三
    					else //(cur == parent->_left) 右左双旋
    					{
    						// g
    						//   p
    						// c
    						RotateR(parent);
    						RotateL(grandfather);
    
    						cur->_col = BLACK;
    						grandfather->_col = RED;
    					}
    					break;
    				}
    			}
    		}
    		_root->_col = BLACK;
    		return make_pair(iterator(newnode), true);
    	}
    
    	iterator Find(const K& key)
    	{
    		Node* cur = _root;
    		KeyOfT kot;
    
    		while (cur)
    		{
    			if (kot(cur->_data) < key)
    			{
    				cur = cur->_right;
    			}
    			else if (kot(cur->_data) > key)
    			{
    				cur = cur->_left;
    			}
    			else
    			{
    				return iterator(cur);
    			}
    		}
    		return End();
    	}
    
    private:
    	void RotateL(Node* parent)
    	{
    		Node* subR = parent->_right;
    		Node* subRL = subR->_left;
    
    		parent->_right = subRL;
    		if (subRL)
    			subRL->_parent = parent;
    
    		Node* grandParent = parent->_parent;
    		subR->_left = parent;
    		parent->_parent = subR;
    
    		if (parent == _root)
    		{
    			_root = subR;
    			subR->_parent = nullptr;
    		}
    		else
    		{
    			if (parent == grandParent->_left)
    			{
    				grandParent->_left = subR;
    			}
    			else
    			{
    				grandParent->_right = subR;
    			}
    			subR->_parent = grandParent;
    		}
    	}
    
    	void RotateR(Node* parent)
    	{
    		Node* subL = parent->_left;
    		Node* subLR = subL->_right;
    
    		parent->_left = subLR;
    		if (subLR)
    			subLR->_parent = parent;
    
    		Node* grandParent = parent->_parent;
    		subL->_right = parent;
    		parent->_parent = subL;
    
    		if (parent == _root)
    		{
    			_root = subL;
    			subL->_parent = nullptr;
    		}
    		else
    		{
    			if (parent == grandParent->_left)
    			{
    				grandParent->_left = subL;
    			}
    			else
    			{
    				grandParent->_right = subL;
    			}
    			subL->_parent = grandParent;
    		}
    	}
    
    
    private:
    	Node* _root = nullptr;
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285

    3. 封装map

    map的底层结构就是红黑树,因此在map中直接封装一棵红黑树,然后将其接口包装下即可。

    	template<class K, class V>
    	class map
    	{
    		struct MapKeyOfT
    		{
    			const K& operator()(const pair<K,V>& kv)
    			{
    				return kv.first;
    			}
    		};
    
    	public:
    		typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::iterator iterator;
    		typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::const_iterator const_iterator;
    
    		iterator begin()
    		{
    			return _t.Begin();
    		}
    
    		iterator end()
    		{
    			return _t.End();
    		}
    
    		pair<iterator, bool> insert(const pair<K, V>& kv)
    		{
    			return _t.Insert(kv);
    		}
    
    		iterator find(const K& key)
    		{
    			return _t.Find(key);
    		}
    
    		V& operator[](const K& key)
    		{
    			pair<iterator, bool> ret = insert(make_pair(key, V()));
    			return ret.first->second;
    		}
    
    	private:
    		RBTree<K, pair<K, V>, MapKeyOfT> _t;
    	};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    4. 封装set

    set的底层为红黑树,因此只需在set内部封装一棵红黑树,即可将该容器实现出来,基本操作与map类似。

    	template<class K>
    	class set
    	{
    		struct SetKeyOfT
    		{
    			const K& operator()(const K& key)
    			{
    				return key;
    			}
    		};
    
    	public:
    		typedef typename RBTree<K, K, SetKeyOfT>::const_iterator iterator;
    		typedef typename RBTree<K, K, SetKeyOfT>::const_iterator const_iterator;
    
    		iterator begin()const
    		{
    			return _t.Begin();
    		}
    
    		iterator end()const
    		{
    			return _t.End();
    		}
    
    		pair<iterator, bool> insert(const K& key)
    		{
    			auto ret = _t.Insert(key);
    			return pair<iterator, bool>(iterator(ret.first._node), ret.second);
    		}
    
    		iterator find(const K& key)
    		{
    			return _t.Find(key);
    		}
    
    
    	private:
    		RBTree<K, K, SetKeyOfT> _t;
    	};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
  • 相关阅读:
    2023年【通信安全员ABC证】找解析及通信安全员ABC证考试总结
    小程序如何实现登录数据持久化
    【Linux从0-1 】之 - 什么是Linux?Linux与Unix有什么区别?Linux的几个主流发行版本
    检查 Oracle 版本的 7 种方法
    Jmeter(十五):jmeter场景的运行方式详解
    基于SSM的手机商城-JAVA【数据库设计、源码、开题报告】
    DPDK 网络加速在 NFV 中的应用
    (免费领源码) Asp.Net#SQL Server校园在线投票系统10557-计算机毕业设计项目选题推荐
    中文人物关系知识图谱(含码源):中文人物关系图谱构建、数据回标、基于远程监督人物关系抽取、知识问答等应用.
    vue如何实现多页面应用网页
  • 原文地址:https://blog.csdn.net/qq_61635026/article/details/126157083