使用红黑树简单实现Set与Map容器

1.AVL树的简单实现

#pragma once 

template<class K,class V>
struct AVLTreeNode
{
	AVLTreeNode* _left;
	AVLTreeNode* _right;
	AVLTreeNode* _parent;

	int _buf;//平衡因子  balance factor: 0,1,-1
	pair<K, V> _kv;
public:
	AVLTreeNode(const pair<K,V>& kv)
		:_left(nullptr)
		,_right(nullptr)
		,_parent(nullptr)
		,_buf(0)
		,_kv(kv)
	{}
};
template<class K,class V>
class AVLTree
{
	typedef AVLTreeNode<K, V> Node;
public:
	
	AVLTree()
		:_root(nullptr)
	{

	}
	//拷贝构造和赋值需要实现深拷贝
	~AVLTree()
	{

	}
	bool Insert(const pair<K, V>& kv)
	{
		if (_root == nullptr)
		{
			_root = new Node(kv);
			return true;
		}
		Node* parent = nullptr, * cur = _root;
		//找到存储的位置
		while (cur)
		{
			if (cur->_kv.first > kv.first)
			{
				parent = cur;
				cur = cur->_left;
			}
			else if (cur->_kv.first < kv.first)
			{
				parent = cur;
				cur = cur->_right;
			}
			else
			{
				return false;
			}


		}
		cur = new Node(kv);
		if (parent->_kv.first < kv.first)
		{
			parent->_right = cur;
			cur->_parent = parent;

		}
		else
		{
			parent->_left = cur;
			cur->_parent = parent;

		}
	
		//控制平衡
		//1.更新平衡因子 -- 新增节点到根节点的路径
		//2.出现一场平衡因子,需要旋转处理

		while (cur->_parent)
		{
			parent = cur ->_parent;
			if (cur == parent->_left)
			{
				parent->_buf--;
				
			}
			else if (cur == parent->_right)
			{
				parent->_buf++;
			}
			if (parent->_buf == 0)//如果parent的平衡因子等于0.则停止更新
			{
				break;
			}
			//如果parent的平衡因子等于1或者 - 1.则继续往上更新  (说明parent所在的子树高度加1)
			else if (parent->_buf == 1 || parent->_buf == -1)	
			{
				cur = cur->_parent;
			}
			//如果parent的平衡因子等于2或者 - 2.已经出现不平衡现象,需要旋转处理
			else if (parent->_buf == 2 || parent->_buf == -2)
			{
				//说明parent所在的子树已经不平衡,需要旋转处理
				if (parent->_buf == -2)
				{
					if (cur->_buf == -1)
					{
						//左边高,右单旋
						RotateR(parent);
					}
					else if(parent->_buf == -2 && cur->_buf == 1)
					{
						RotateLR(parent);
					}
					
				}
				else //parent->_buf == 2
				{
					if (cur->_buf == 1)
					{
						//右边高,左单旋
						RotateL(parent);
					}
					else if(parent->_buf == 2 && cur->_buf == -1)
					{
						RotateRL(parent);
					}
				}
				break;
			}
			else	//说明在插入结点之前,树已经不平衡了,或者是bf出错,需要检查其他逻辑错误
			{
				assert(false);
			}
		}
		return true;
	}
	void RotateLR(Node* parent)//左右双旋
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		int bf = subLR->_buf;
		RotateL(parent->_left);
		RotateR(parent);
		//..._buf的重置问题
		if (bf == 0)
		{
			parent->_buf = 0;
			subL->_buf = 0;
			subLR->_buf = 0;
		}
		else if (bf == -1)
		{
			parent->_buf = 1;
			subL->_buf = 0;
			subLR->_buf = 0;
		}
		else if (bf == 1)
		{
			parent->_buf = 0;
			subL->_buf = -1;
			subLR->_buf = 0;
		}
		else
		{
			assert(false);
		}
	}
	void RotateRL(Node* parent)//右左双旋
	{
		//根据subRL节点的平衡因子_buf来识别三种情况。
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		int bf = subRL->_buf;
		RotateR(parent->_right);
		RotateL(parent);
		//..._buf的重置问题
		if (bf == 0)
		{
			parent->_buf = 0;
			subR->_buf = 0;
			subRL->_buf = 0;
		}
		else if (bf == -1)
		{
			parent->_buf = 0;
			subR->_buf = 1;
			subRL->_buf = 0;
		}
		else if (bf == 1)
		{
			parent->_buf = -1;
			subR->_buf = 0;
			subRL->_buf = 0;
		}
		else
		{
			assert(false);
		}
	}
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		Node* parentParent = parent->_parent;
		parent->_left = subLR;

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

			subL->_parent = parentParent;
		}
		subL->_buf = parent->_buf = 0;
	}
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		Node* parentParent = parent->_parent;
		parent->_right = subRL;

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

			subR->_parent = parentParent;
		}
		subR->_buf = parent->_buf = 0;
	}
	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) ;
	}
	bool _IsBlance(Node* root)
	{
		if (root == nullptr)
			return true;

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

		return abs(leftHeight - rightHeight) < 2
			&& _IsBlance(root->_left)
			&& _IsBlance(root->_right);
	}
	bool IsBlance()
	{
		return	_IsBlance(_root);
	}
	void _Inorder(const Node* root)
	{
		if (root == nullptr)
			return;
		_Inorder(root->_left);
		cout << (root->_kv).first << ": " << (root->_kv).second << endl;
		_Inorder(root->_right);
	}
	void Inorder()
	{
		_Inorder(_root);
	}
	Node* Find(const K& key)
	{
		return nullptr;
	}
	bool Erase(const K& key)
	{
		return false;
	}
private:
	Node* _root;
};


2.红黑树的简单实现

#pragma once
#pragma once
enum Colour {
	RED,
	BLACK
};
template <class T>
struct RBTreeNode
{
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	T _data;
	
	Colour _colour;

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

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)
		{
			Node* min = _node->_right;
			while (min->_left)
			{
				min = min->_left;
			}
			_node = min;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	Self& operator--()
	{
		if (_node->_left)
		{
			Node* min = _node->_left;
			while (min->_right)
			{
				min = min->_right;
			}
			_node = min;
		}
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_left)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_node = parent;
		}
		return *this;
	}

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

//set RBTree<K,K>
//map RBTree pair<K, V>
template<class K, class T, class KeyOfT>
struct RBTree
{
	typedef RBTreeNode<T>  Node;
public:
	typedef RBTreeIterator<T, T&, T*> iterator;
	typedef RBTreeIterator<T, const T&, const T*> const_iterator;

	iterator begin()
	{
		Node* min = _root;
		while (min && min->_left)
		{
			min = min->_left;
		}
		return iterator(min);
	}
	iterator end()
	{
		return iterator(nullptr);
	}
	RBTree()
		:_root(nullptr)
	{}

	RBTree(const RBTree<K, T, KeyOfT>& t)
	{
		_root = Copy(t._root);
	}
	
	RBTree<K, T, KeyOfT>& operator=(RBTree<K, T, KeyOfT> t)
	{
		swap(_root, t._root);
		return *this;
	}

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


	pair<iterator, bool> Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_colour = BLACK;
			return make_pair(iterator(_root), true);
		}


		KeyOfT kot;


		Node* parent = nullptr, * cur = _root;
		//找到存储的位置
		while (cur)
		{
			if (kot(cur->_data) > kot(data))
			{
				parent = cur;
				cur = cur->_left;
			}
			else if (kot(cur->_data) < kot(data))
			{
				parent = cur;
				cur = cur->_right;
			}
			else
			{
				return make_pair(iterator(cur), false);
			}
		}
		cur = new Node(data);
		Node* newnode = cur;
		cur->_colour = RED;//新增节点
		if (kot(parent->_data) < kot(data))
		{
			parent->_right = cur;
			cur->_parent = parent;

		}
		else
		{
			parent->_left = cur;
			cur->_parent = parent;

		}


		//控制平衡
		while (parent && parent->_colour == RED)
		{
			//一定有祖父
			Node* grandfather = parent->_parent;
			if (parent == grandfather->_left)
			{
				Node* uncle = grandfather->_right;
				//1. uncle存在且为红
				if (uncle && uncle->_colour == RED)
				{
					//变色+继续向上处理
					parent->_colour = uncle->_colour = BLACK;
					grandfather->_colour = RED;

					cur = grandfather;
					parent = cur->_parent;
				}
				else//2.uncle不存在/存在且为黑
				{
					//         g
					//		p
					//	cur
					//右单旋
					if (cur == parent->_left)
					{
						RotateR(grandfather);
						parent->_colour = BLACK;
						grandfather->_colour = RED;
					}
					//         g
					//		p
					//		   cur
					//左右双旋
					else
					{
						RotateL(parent);
						RotateR(grandfather);
						cur->_colour = BLACK;
						grandfather->_colour = RED;
					}
					break;
				}
			}

			else
			{
				Node* uncle = grandfather->_left;
				//1. uncle存在且为红
				if (uncle && uncle->_colour == RED)
				{
					//变色+继续向上处理
					parent->_colour = uncle->_colour = BLACK;
					grandfather->_colour = RED;

					cur = grandfather;
					parent = cur->_parent;
				}
				else//2.uncle不存在/存在且为黑
				{
					//         g
					//				p
					//					cur
					//左单旋
					if (cur == parent->_right)
					{
						RotateL(grandfather);
						parent->_colour = BLACK;
						grandfather->_colour = RED;
					}
					//         g
					//				p
					//		   cur		
					//右左双旋
					else
					{
						RotateR(parent);
						RotateL(grandfather);
						cur->_colour = BLACK;
						grandfather->_colour = RED;
					}
					break;
				}
			}
		}
		_root->_colour = BLACK;
		return make_pair(iterator(newnode), true);
	}
	bool _IsBalance(Node* root, int banchmark, int blackNum)
	{
		if (root == nullptr)
		{
			return (banchmark == blackNum);
		}
		if ((root->_colour == RED) && (root->_parent->_colour == RED))
		{
			cout << "出现连续红节点" << endl;
			return false;
		}
		if (root->_colour == BLACK)
			blackNum++;
		return _IsBalance(root->_left, banchmark, blackNum)
			&& _IsBalance(root->_right, banchmark, blackNum);

	}

	~RBTree()
	{
		Destory(_root);
		_root = nullptr;
	}
private:

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

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

			subL->_parent = parentParent;
		}
		
	}
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		Node* parentParent = parent->_parent;
		parent->_right = subRL;

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

			subR->_parent = parentParent;
		}
	}
	
	void Destory(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		Destory(root->_left);
		Destory(root->_right);
		delete root;
	}
	Node* Copy(Node* root)
	{
		if (root == nullptr)
			return nullptr;
		Node* newRoot = new Node(root->_data);
		//newRoot->
		newRoot->_colour = root->_colour;
		newRoot->_left = Copy(root->_left);
		newRoot->_right = Copy(root->_right);
		if (newRoot->_left)
			newRoot->_left->_parent = newRoot;
		
		if (newRoot->_right)
			newRoot->_right->_parent = newRoot;
		
		return newRoot;
	}
	

private:
	Node* _root;
};

3.使用红黑树简单实现set

#pragma once
#include"RBTree.h"

namespace yqx
{
	template<class K>
	class set
	{
	public:
		struct SetKeyOfT
		{
			const K& operator()(const K& k)
			{
				return k;
			}
		};
		typedef typename RBTree<K, K, SetKeyOfT>::iterator iterator;

		iterator begin()
		{
			return _t.begin();
		}
		iterator end()
		{
			return _t.end();
		}
		
		pair<iterator, bool> insert(const K& key)
		{
			return _t.Insert(key);
		}
	private:
		RBTree<K, K, SetKeyOfT> _t;
	};

	void test_set()
	{
		set<int> s;
		s.insert(1);
		s.insert(2);
		s.insert(3);
		s.insert(4);
		s.insert(5);
		s.insert(6);

		set<int>::iterator it = s.begin();
		while (it != s.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;
		cout << "set:" << endl;
		for (auto e : s)
		{
			cout << e << " ";
		}
		cout << endl;
		set<int> copy(s);
		cout << "set拷贝copy:" << endl;
		for (auto e : copy)
		{
			cout << e << " ";
		}
		cout << endl;
	}
}


4.使用红黑树简单实现map

#pragma once
#include"RBTree.h"
namespace yqx
{
	template <class K, class V>
	class map
	{
		
		public:
			struct MapKeyOfT
			{
				const K& operator()(const pair<K, V>& kv)
				{
					return kv.first;
				}
			};
			typedef typename RBTree<K, pair<K, V>, MapKeyOfT>::iterator 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)
			{
				auto ret = _t.Insert(make_pair(key, V()));
				return ret.first->second;
			}
		private:
			RBTree<K, pair<K, V>, MapKeyOfT> _t;

		
	};
	void test_map()
	{
		map<int, int> m;
		m.insert(make_pair(3, 3));
		m.insert(make_pair(1, 3));
		m.insert(make_pair(4, 5));
		m.insert(make_pair(6, 8));
		m.insert(make_pair(3, 10));
		m.insert(make_pair(4, 6));
		map<string, string> dict;
		dict.insert(make_pair("sort", "排序"));
		dict.insert(make_pair("apple", "苹果"));
		dict.insert(make_pair("map", "地图"));
		dict["left"];
		dict["left"] = "左边";
		dict["map"] = "地图,映射";
		auto it = dict.begin();
		cout << "map:" << endl;
		while (it != dict.end())
		{
			cout << it->first << ": " << it->second << endl;
			++it;
		}
		cout << endl;
		map<string, string> copy_map(dict);
		cout << "copy_map:" << endl;
		for (auto e : copy_map)
		{
			cout << e.first << ": " << e.second << endl;
		}
		cout << endl;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

倚心

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

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

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

打赏作者

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

抵扣说明:

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

余额充值