红黑树封装map和set(模拟实现)

troop主页
临近五一放假,祝大家节日快乐,我们的学习还在路上!!
在前面一章我们已经实现出了红黑树的基本框架,现在我们要有这个底层结构去封装map和set。

一 红黑树的迭代器

但在这之前我们要先把红黑树的迭代器实现出来,因为map和set也是有迭代器的。
迭代器常用的有这么几个"-> * ++ == !="这个几个中++的实现是重点,其他的较为简单。

1.2 operator++

在这里插入图片描述

要理解++首先我们要知道++后下一个节点是谁。当然红黑树走的是中序遍历,
举两个例子,假如it现在是在13的位置上,那么++it下一个点是谁?
在这里插入图片描述

中序:左子树+根+右子树。所以当it在13的位置时说明他的左子树已经全部遍历完成了,现在就要到右子树的最左节点也就是15.
那如果it现在在15的位置时,++it呢?可以看见,15的右子树为空,那就要寻找他的父亲节点也就是17.
分析完毕,我们来总结一下。

  1. 当it指向的当前节点的右子树不为空,那就去寻找此节点右子树的最左节点
  2. 当it指向的当前节点的右子树为空,说明这个节点的中序遍历已经结束了,要向上返回了,下一个节点就是孩子=父亲的左,这个节点。
    这里还有一些细节问题。当我们在向上返回的时候,如果cur走到了根节点,那么parent这个节点就会出现越界访问的问题,所以在写条件的时候要加上这一点。
Self& operator++()
	{
		if (_node->_right && _node)//右子树不为空
		{
			Node* subLeft = _node->_left;
			while (subLeft->_left)
			{
				subLeft = subLeft->_left;
			}
			_node = subLeft;
		}
		else//右子树为空
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (cur == parent->_right && parent)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}

1.3 迭代器完整代码

template<class T>
struct RBTreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T> Self;
	Node* _node;

	T* operator->()
	{
		return &_node->_data;
	}
	T& operator*()
	{
		return _node->_data;
	}
	Self& operator++()
	{
		if (_node->_right && _node)//右子树不为空
		{
			Node* subLeft = _node->_left;
			while (subLeft->_left)
			{
				subLeft = subLeft->_left;
			}
			_node = subLeft;
		}
		else//右子树为空
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (cur == parent->_right && parent)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}

	bool operator == (const Self & s)
	{
		return _node == s._node;
	}
};

二 封装

这一部分刚开始看可能会有些晕,因为我们要在三个文件中来回的更改代码。

2.1改造红黑树

因为关联式容器中存储的是<key,value>的键对值,因此我们不能单纯的写K和V。
这里的value对于map和set来说是完全不一样的。

对于set来说value就是K
对于map来说value就是pair<K,V>

那么对于模板来说set就是<K,K>
对于map就是<K,pair<K,V>>

//template<class K, class V>
template<class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	//pair<K, V> _kv;
	T _data;
	Colour _col;

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

这里改造前的代码我搞成了注释,方便大家观察。下面有K,V的也都改成了T。

现在我们把map和set写出来,再梳理一遍
在这里插入图片描述
但此时又产生了一个新的问题,我们的比较大小怎么办?我们预期的比较大小是只有first比较也就是K比较,而seco是不参与比较的。我们先来看一看库里面的pair有没有比较。
在这里插入图片描述
库里面的pair还有second的比较这是不符合我们的预期的,那么我们要怎么做呢?
我们可以自己写一个仿函数来进行比较。写一个仿函数
1.如果是set就取出key

		struct setKeyOfT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};

2.如果是map取出pair里面的key

		struct mapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};

我们在红黑树的类型中加入这个仿函数,并且在每个需要用到key的位置上加入这个仿函数。

三 代码全

1 RBTree

#pragma once
#include<vector>
#include<iostream>
using namespace std;
enum Colour
{
	RED,
	BLACK
};

//template<class K, class V>
template<class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	//pair<K, V> _kv;
	T _data;
	Colour _col;

	RBTreeNode(const T data)
		:_left(nullptr)
		, _right(nullptr)
		, _parent(nullptr)
		, _data(data)
		, _col(RED)
	{}
};
template<class T>
struct RBTreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T> Self;
	Node* _node;

	T* operator->()
	{
		return &_node->_data;
	}
	T& operator*()
	{
		return _node->_data;
	}
	Self& operator++()
	{
		if (_node->_right && _node)//右子树不为空
		{
			Node* subLeft = _node->_left;
			while (subLeft->_left)
			{
				subLeft = subLeft->_left;
			}
			_node = subLeft;
		}
		else//右子树为空
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (cur == parent->_right && parent)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	bool operator!=(const Self& s)
	{
		return _node != s._node;
	}

	bool operator == (const Self & s)
	{
		return _node == s._node;
	}
};
template<class K, class T, class KeyOfT>
class RBTree
{
	typedef RBTreeNode<T> Node;
	
public:
	typedef RBTreeIterator<T> iterator;
	iterator begin()
	{
		Node* subLeft = _root;
		while (subLeft && subLeft->_left)
		{
			subLeft = subLeft->_left;
		}
		return iterator(subLeft);
	}
	iterator end()
	{
		return iterator(nullptr);
	}
	
	bool Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_col = BLACK;
			return 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 false;
			}
		}

		cur = new Node(data); // 红色的
		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;
			if (parent == grandfather->_left)
			{
				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    u
						// c
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//       g
						//    p     u
						//      c
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
			else
			{
				Node* uncle = grandfather->_left;
				// 情况一:叔叔存在且为红
				if (uncle && uncle->_col == RED)
				{
					// 变色
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上处理
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					// 情况二:叔叔不存在或者存在且为黑
					// 旋转+变色
					//      g
					//   u     p
					//            c
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//		g
						//   u     p
						//      c
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}

					break;
				}
			}
		}

		_root->_col = BLACK;

		return true;
	}


	void RotateL(Node* parent)
	{

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

		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;

		subR->_left = parent;
		Node* ppnode = parent->_parent;
		parent->_parent = subR;

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

	void RotateR(Node* parent)
	{

		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;

		subL->_right = parent;

		Node* ppnode = parent->_parent;
		parent->_parent = subL;

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

	void _InOrder(Node* root)
	{
		if (root == nullptr)
			return;

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

	void InOrder()
	{
		_InOrder(_root);
	}

	bool Check(Node* cur, int blackNum, int refBlackNum)
	{
		if (cur == nullptr)
		{
			if (refBlackNum != blackNum)
			{
				cout << "黑色节点的数量不相等" << endl;
				return false;
			}

			//cout << blackNum << endl;
			return true;
		}

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

		if (cur->_col == BLACK)
			++blackNum;

		return Check(cur->_left, blackNum, refBlackNum)
			&& Check(cur->_right, blackNum, refBlackNum);
	}

	bool IsBalance()
	{
		if (_root && _root->_col == RED)
			return false;

		int refBlackNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK)
				refBlackNum++;

			cur = cur->_left;
		}

		return Check(_root, 0, refBlackNum);
	}

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

	//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;
	//}

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

	//int GetRotateSize()
	//{
	//	return rotateSize;
	//}

private:
	Node* _root;
	//int rotateSize = 0;
};

//void TestRBTree1()
//{
//	//int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
//	int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14,16, 3, 7, 11, 9, 26, 18, 14, 15 };
//	RBTree<int, int> t;
//	for (auto e : a)
//	{
//		t.Insert(make_pair(e, e));
//
//		// 1、先看是插入谁导致出现的问题
//		// 2、打条件断点,画出插入前的树
//		// 3、单步跟踪,对比图一一分析细节原因
//		//cout << e << "->" << t.IsBalance() << endl;
//	}
//
//	t.InOrder();
//	cout << t.IsBalance() << endl;
//}

2 map

#pragma once
#include"RBTree.h"
namespace yjt
{
	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;

		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}
		bool insert(const pair<K,V>& kv)
		{
			return _t.Insert(kv);
		}
	private:
		RBTree<K, pair<K, V>, mapKeyOfT> _t;
	};
	void test_map1()
	{
		map<int,int> m;
		int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
		for (auto e : a)
		{
			m.insert(make_pair(e, e));
		}

		map<int,int>::iterator it = m.begin();
		while (it != m.end())
		{
			//if(*it % 2 == 0)
			//	*it += 100;

			cout << it->first << ":" << it->second << endl;
			++it;
		}
		cout << endl;
	}
}

3 set

#pragma once
#include"RBTree.h"
namespace yjt
{
	template<class K>
	class set
	{
		struct setKeyOfT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};
	public:
		typedef typename RBTree<K,K, setKeyOfT>::iterator iterator;

		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}
		bool insert(const K& key)
		{
			return _t.Insert(key);
		}
	private:
		RBTree<K, K, setKeyOfT> _t;
	};
	void test_set1()
	{
		set<int> s;
		int a[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
		for (auto e : a)
		{
			s.insert(e);
		}

		set<int>::iterator it = s.begin();
		while (it != s.end())
		{
			//if(*it % 2 == 0)
			//	*it += 100;

			cout << *it << " ";
			++it;
		}
		cout << endl;
	}
}


四 总结

这个就需要多写代码去理解,因为代码都普遍比价大一些。

  • 19
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tpoog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值