红黑树的模拟实现

一、介绍

1. 概念

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

2. 性质

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

3. 结点定义

enum Colour//两种颜色
{
	RED,
	BLACK
};

//定义红黑树的结点
template
struct RBTreeNode
{
	RBTreeNode* _left;
	RBTreeNode* _right;
	RBTreeNode* _parent;
	pair _kv;
	Colour _col;

	RBTreeNode(const pair& kv)
		:_left(nullptr)
		,_right(nullptr)
		,_parent(nullptr)
		,_kv(kv)
		,_col(RED)
	{}
};

二、插入的3种情况

(一)情况1

  • 因为cur为当前插入新结点(红色),而不能有连在一起的红色节点,所以parent结点需要变成黑色
  • 控制每条路径上黑节点的数量相同,那么就要把uncle变黑
  • grandparent如果不是根节点,需要继续向上调整,所以grandparent需要变成红色

红黑树的模拟实现_第1张图片

//情况1:uncle存在且为红色
if (uncle != nullptr && uncle->_col == RED)
{
	//调整颜色
	parent->_col = uncle->_col = BLACK;
	grandfather->_col = RED;

	//继续往上调整
	cur = grandfather;
	parent = cur->_parent;
}

 

(二)情况2

红黑树的模拟实现_第2张图片

//情况2
if (cur == parent->_left)
{
	//             grandfather
	//        parent
	//    cur
	RotateR(grandfather);//右旋转
	//调整颜色
	parent->_col = BLACK;
	grandfather->_col = RED;

}

 

(三)情况3

红黑树的模拟实现_第3张图片

 

 

else//cur在parent的右边
{
	//             grandfather
	//        parent
	//              cur
	RotateL(parent);//先左旋转
	RotateR(grandfather);//再右旋转
	//调整颜色
	cur->_col = BLACK;
	grandfather->_col = RED;
}

(四)插入代码

bool Insert(const pair& kv)
{
	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//已经存在一样的值,直接返回false
		{
			return false;
		}
	}

	//链接
	cur = new Node(kv);
	cur->_col = RED;
	if (parent->_kv.first < kv.first)
	{
		parent->_right = cur;
		cur->_parent = parent;
	}
	else
	{
		parent->_left = cur;
		cur->_parent = parent;
	}

	//调整
	while (parent && parent->_col == RED)//如果父亲结点是黑色直接结束
	{
		Node* grandfather = parent->_parent;
		if (parent == grandfather->_left)
		{
			//         grandfather
			//      parent     uncle
			//   cur
			//
			Node* uncle = grandfather->_right;
			//情况1:uncle存在且为红色
			if (uncle != nullptr && uncle->_col == RED)
			{
				//调整颜色
				parent->_col = uncle->_col = BLACK;
				grandfather->_col = RED;

				//继续往上调整
				cur = grandfather;
				parent = cur->_parent;
			}
			else//uncle不存在或者uncle为黑色
			{   //情况2
				if (cur == parent->_left)
				{
					//             grandfather
					//        parent
					//    cur
					RotateR(grandfather);//右旋转
					//调整颜色
					parent->_col = BLACK;
					grandfather->_col = RED;

				}
				else//cur在parent的右边
				{
					//             grandfather
					//        parent
					//              cur
					RotateL(parent);//先左旋转
					RotateR(grandfather);//再右旋转
					//调整颜色
					cur->_col = BLACK;
					grandfather->_col = RED;
				}
				break;
			}
		}
		else//parent == grandfather->_right
		{
			Node* uncle = grandfather->_left;

			//         g
			//      u    p
			//             c
			//
			//情况1:uncle存在且为红色
			if (uncle != nullptr && uncle->_col == RED)
			{
				//调整颜色
				parent->_col = uncle->_col = BLACK;
				grandfather->_col = RED;

				//继续往上调整
				cur = grandfather;
				parent = cur->_parent;
			}
			else//uncle不存在或者uncle为黑色
			{
				if (cur == parent->_right)
				{
					//           g
					//              p
					//                 c
					RotateL(grandfather);
					//调整颜色
					parent->_col = BLACK;
					grandfather->_col = RED;
				}
				else
				{
					//         g
					//             p
					//           c
					RotateR(parent);//先右旋
					RotateL(grandfather);//再左旋

					//调整颜色
					cur->_col = BLACK;
					grandfather->_col = RED;

				}
				break;
			}
		}
	}
	_root->_col = BLACK;
	return true;
}

三、判断是否近似平衡

//	// 根节点->当前节点这条路径的黑色节点的数量
bool Check(Node* root, int blacknum, const int refVal)
{
	if (root == nullptr)//走到了一条路径的尽头
	{
		if (blacknum != refVal)
		{
			cout << "存在黑色节点数量不相等的路径" << endl;
			return false;
		}

		return true;
	}

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

	if (root->_col == BLACK)
	{
		++blacknum;
	}

	return Check(root->_left, blacknum, refVal)
		&& Check(root->_right, blacknum, refVal);
}

bool IsBalance()//判断是否平衡
{
	if (_root == nullptr)
		return true;

	if (_root->_col == RED)//根结点如果是红色
		return false;

	int refVal = 0;
	Node* cur = _root;
	while (cur)//计算其中一条路径上的黑色节点数量作为参考值
	{
		if (cur->_col == BLACK)
		{
			++refVal;
		}

		cur = cur->_left;
	}

	int blacknum = 0;
	return Check(_root, blacknum, refVal);
}

四、完整代码

#pragma once
#include
#include
#include
using namespace std;
enum Colour//两种颜色
{
	RED,
	BLACK
};

//定义红黑树的结点
template
struct RBTreeNode
{
	RBTreeNode* _left;
	RBTreeNode* _right;
	RBTreeNode* _parent;
	pair _kv;
	Colour _col;

	RBTreeNode(const pair& kv)
		:_left(nullptr)
		,_right(nullptr)
		,_parent(nullptr)
		,_kv(kv)
		,_col(RED)
	{}
};

template
class RBTree
{
	typedef RBTreeNode Node;
public:
	bool Insert(const pair& kv)
	{
		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//已经存在一样的值,直接返回false
			{
				return false;
			}
		}

		//链接
		cur = new Node(kv);
		cur->_col = RED;
		if (parent->_kv.first < kv.first)
		{
			parent->_right = cur;
			cur->_parent = parent;
		}
		else
		{
			parent->_left = cur;
			cur->_parent = parent;
		}

		//调整
		while (parent && parent->_col == RED)//如果父亲结点是黑色直接结束
		{
			Node* grandfather = parent->_parent;
			if (parent == grandfather->_left)
			{
				//         grandfather
				//      parent     uncle
				//   cur
				//
				Node* uncle = grandfather->_right;
				//情况1:uncle存在且为红色
				if (uncle != nullptr && uncle->_col == RED)
				{
					//调整颜色
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;
					
					//继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else//uncle不存在或者uncle为黑色
				{   //情况2
					if (cur == parent->_left)
					{
						//             grandfather
						//        parent
						//    cur
						RotateR(grandfather);//右旋转
						//调整颜色
						parent->_col = BLACK;
						grandfather->_col = RED;

					}
					else//cur在parent的右边
					{
						//             grandfather
						//        parent
						//              cur
						RotateL(parent);//先左旋转
						RotateR(grandfather);//再右旋转
						//调整颜色
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
			else//parent == grandfather->_right
			{
				Node* uncle = grandfather->_left;
				
				//         g
				//      u    p
				//             c
				//
				//情况1:uncle存在且为红色
				if (uncle != nullptr && uncle->_col == RED)
				{
					//调整颜色
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;

					//继续往上调整
					cur = grandfather;
					parent = cur->_parent;
				}
				else//uncle不存在或者uncle为黑色
				{
					if (cur == parent->_right)
					{
						//           g
						//              p
						//                 c
						RotateL(grandfather);
						//调整颜色
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//         g
						//             p
						//           c
						RotateR(parent);//先右旋
						RotateL(grandfather);//再左旋

						//调整颜色
						cur->_col = BLACK;
						grandfather->_col = RED;

					}
					break;
				}
			}
		}
		_root->_col = BLACK;
		return true;
	}

	// 根节点->当前节点这条路径的黑色节点的数量
	bool Check(Node* root, int blacknum, const int refVal)
	{
		if (root == nullptr)//走到了一条路径的尽头
		{
			if (blacknum != refVal)
			{
				cout << "存在黑色节点数量不相等的路径" << endl;
				return false;
			}

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

		if (root->_col == BLACK)
		{
			++blacknum;
		}

		return Check(root->_left, blacknum, refVal)
			&& Check(root->_right, blacknum, refVal);
	}

	bool IsBalance()//判断是否平衡
	{
		if (_root == nullptr)
			return true;

		if (_root->_col == RED)//根结点如果是红色
			return false;

		int refVal = 0;
		Node* cur = _root;
		while (cur)//计算其中一条路径上的黑色节点数量作为参考值
		{
			if (cur->_col == BLACK)
			{
				++refVal;
			}

			cur = cur->_left;
		}

		int blacknum = 0;
		return Check(_root, blacknum, refVal);
	}
	void RotateL(Node* parent)//左单旋
	{
		Node* parentParent = parent->_parent;
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		parent->_right = subRL;
		subR->_left = parent;

		//更新调整结点的父指针指向
		parent->_parent = subR;
		//subRL->_parent = parent;错误,没有判断subRL是不是为空
		if (subRL != nullptr)
		{
			subRL->_parent = parent;
		}

		if (_root == parent)
		{
			_root = subR;
			subR->_parent = nullptr;
		}
		else
		{
			if (parentParent->_left == parent)
			{
				parentParent->_left = subR;
			}
			else
			{
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}

		//更新平衡因子
		//parent->_bf = subR->_bf = 0;
	}

	void RotateR(Node* parent)//右单旋
	{
		Node* parentParent = parent->_parent;
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		parent->_left = subLR;
		//更新调整结点的父指针指向
		if (subLR != nullptr)
		{
			subLR->_parent = parent;
		}

		subL->_right = parent;
		//更新调整结点的父指针指向
		parent->_parent = subL;


		if (_root == parent)
		{
			_root = subL;
			subL->_parent = nullptr;
		}
		else
		{
			//需要先判断subR应该链接在parentParent的哪一侧
			if (parentParent->_left == parent)
			{
				parentParent->_left = subL;
			}
			else
			{
				parentParent->_right = subL;
			}
			subL->_parent = parentParent;
		}
		//更新平衡因子
		//parent->_bf = subL->_bf = 0;
	}
	void InOrder()//中序遍历
	{
		_InOrder(_root);
		cout << endl;
	}
	void _InOrder(Node* root)//中序遍历
	{
		if (root == nullptr)
		{
			return;
		}

		_InOrder(root->_left);
		cout << root->_kv.first << " ";
		_InOrder(root->_right);
	}

	int Height()
	{
		return _Height(_root);
	}

	int _Height(Node* root)
	{
		if (root == nullptr)
			return 0;

		int leftHeight = _Height(root->_left);
		int rightHeight = _Height(root->_right);

		return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
	}

	size_t Size()
	{
		return _Size(_root);
	}

	size_t _Size(Node* root)
	{
		if (root == NULL)
			return 0;

		return _Size(root->_left)
			+ _Size(root->_right) + 1;
	}

	Node* Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < key)
			{
				cur = cur->_right;
			}
			else if (cur->_kv.first > key)
			{
				cur = cur->_left;
			}
			else
			{
				return cur;
			}
		}

		return NULL;
	}
private:
	Node* _root = nullptr;
};

1. 测试用例1

#include"RBTree.h"
int main()
{
	//int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
	//int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
	int a[] = { 790,760,969,270,31,424,377,24,702 };
	RBTree t;
	for (auto e : a)
	{
		if (e == 702)
		{
			int i = 0;
		}
	
		cout << "Insert:" << e << "->";
		t.Insert(make_pair(e, e));
		cout << t.IsBalance() << endl;
	}
	t.InOrder();
	
	cout << t.IsBalance() << endl;
	
	return 0;
}

2. 测试用例2

#include"RBTree.h"

int main()
{
	const int N = 100000;
	vector v;
	v.reserve(N);
	srand(time(0));

	for (size_t i = 0; i < N; i++)
	{
		v.push_back(rand() + i);
		//cout << v.back() << endl;
	}

	size_t begin2 = clock();
	RBTree t;
	for (auto e : v)
	{
		if (e == 29365)
		{
			int i = 0;
		}

		//cout << "Insert:" << e << "->";
		t.Insert(make_pair(e, e));
		//cout << t.IsBalance() << endl;
	}
	size_t end2 = clock();

	cout << "Insert:" << end2 - begin2 << endl;

	cout << t.IsBalance() << endl;
	cout << t.Height() << endl;
	cout << t.Size() << endl;

	size_t begin1 = clock();
	for (auto e : v)
	{
		t.Find(e);
	}

	for (size_t i = 0; i < N; i++)
	{
		t.Find((rand() + i));
	}

	size_t end1 = clock();

	cout << "Find:" << end1 - begin1 << endl;

	return 0;
}

你可能感兴趣的:(数据结构(精),算法,开发语言,数据结构,c++)