【数据结构】红黑树

目录

一、红黑树

1.1 基本概念

1.2 红黑树与AVL树的比较

二、结构和操作

2.1 节点定义

2.2 节点的插入操作

2.3 红黑树的迭代器

2.4 红黑树的模拟实现

三、set、 map的模拟实现


一、红黑树

1.1 基本概念

红黑树是一种二叉搜索树,但在每个结点上增加一个存储位表示结点的颜色,可以是Red或
Black。 

红黑树满足以下性质:

  1. 节点颜色:每个节点要么是黑色,要么是红色。
  2. 根节点:根节点是黑色。
  3. 颜色限制:如果一个节点是红色的,则它的子节点必须是黑色的(不存在两个连续的红色节点)。
  4. 叶子节点:每个叶子节点(NIL 节点,即空节点)都是黑色的。
  5. 黑节点数量:对于每个节点,从该节点到其后代叶子节点的简单路径上,黑色节点的数量是相同的。

这些性质保证了红黑树的关键特性:任何从根到叶子的路径上,最长的路径不会超过最短路径的两倍长。因此,红黑树是一种高效的自平衡二叉搜索树,适用于需要频繁插入、删除和查找操作的场景。

注:

  1. 最短路径和最长路径不一定会存在。
    最短路径:全黑
    最长路径:一黑一红间隔
  2. 假设每条路径都有N个黑色节点,每条路径的节点数量在[N,2*N]之间。

1.2 红黑树与AVL树的比较

红黑树和AVL树都是自平衡二叉搜索树,但它们在平衡策略和性能方面有所不同。

平衡性:AVL树是严格平衡的,它要求左右子树的高度差不超过1。而红黑树是近似平衡的,它通过染色和旋转来维护平衡,允许最长的路径不会超过最短路径的两倍长。相对而言,红黑树的平衡性要稍弱一些,但仍然能够在大多数情况下保持较好的平衡。

插入和删除操作的效率:由于AVL树是严格平衡的,因此插入和删除操作可能需要进行更多的旋转来调整树的结构,以维持平衡。相比之下,红黑树的插入和删除操作可能需要更少的旋转操作,因为它允许一定程度的不平衡。因此,红黑树在插入和删除操作方面可能具有更好的性能。

查询操作的效率:由于红黑树在插入和删除操作上具有更好的性能,但在查询操作上与AVL树相当。这是因为红黑树的高度相对较大,但仍保持在较小的范围内,使得查询操作的时间复杂度仍然是O(log n),其中n是树中节点的数量。而AVL树由于严格的平衡性要求,在某些情况下可能会略微优于红黑树。


二、结构和操作

2.1 节点定义

enum Colour
{
	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(RED)
	{}
};

2.2 节点的插入操作

按照二叉搜索的树规则插入新节点,新节点是红色,有两种情况:
1、插入节点的父亲是黑色,那么就结束了。没有违反任何规则。
2、插入节点的父亲是红色的,那么存在连续的红色节点,违反规则3,需要处理。

设新插入的节点为cur,其父亲节点为p,祖父节点为p,叔叔节点为u,根据各节点颜色的不同可分为以下几种情况:

情况1:cur为红,p为红,g为黑,存在且为红
解决方式:将p,u改为黑,g改为红,然后把g当成cur,继续向上调整。
注意:此处所看到的树,可能是一棵完整的树,也可能是一棵子树

情况二:cur为红,p为红,g为黑,u不存在
解决方案:若p为g的左孩子,cur为p的左孩子,则g进行右单旋转;
相反,p为g的右孩子,cur为p的右孩子,则g进行左单旋转;
p、g变色--p变黑,g变红

情况三:cur为红,p为红,g为黑,u存在且为黑
c为包含一个黑色节点红黑树

解决方案:旋转+变色
若p为g的左孩子,cur为p的左孩子,则g进行右单旋转;
相反,p为g的右孩子,cur为p的右孩子,则g进行左单旋转;
p、g变色--p变黑,g变红

情况四:cur为红,p为红,g为黑,u不存在/u存在且为黑

解决方案:p为g的左孩子,cur为p的右孩子,则针对p做左单旋转;
相反,p为g的右孩子,cur为p的左孩子,则针对p做右单旋转;
转换成情况二和情况三

2.3 红黑树的迭代器

template <class T, class Ref, class Ptr>
struct __TreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef __TreeIterator<T, Ref, Ptr> Self;
	Node* _pnode;

	__TreeIterator(Node* pnode)
		:_pnode(pnode)
	{}

	Ref operator*()
	{
		return _pnode->_data;
	}

	Ptr operator->()
	{
		return &_pnode->_data;
	}
	
	Self& operator--()
	{
		
		if (_pnode->_left)//左子树不为空,下一节点为左子树的最右节点
		{
			Node* cur = _pnode->_left;
			while (cur->_right)
			{
				cur = cur->_right;
			}
			_pnode = cur;
		}
		else//左子树为空,找孩子是父亲右的那个祖先
		{
			Node* cur = _pnode;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_left)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_pnode = parent;
		}
		return *this;
	}
	
	Self& operator++()
	{
		if (_pnode->_right)
		{
			//右子树不为空,下一个节点为右子树的最左节点
			Node* cur = _pnode->_right;
			while (cur->_left)
			{
				cur = cur->_left;
			}
			_pnode = cur;
		}
		else
		{
			//右子树为空,下一个节点为节点为父亲左孩子的那个祖先
			Node* cur = _pnode;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_pnode = parent;
		}
		return *this;
	}

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

2.4 红黑树的模拟实现

#pragma once

enum Colour
{
	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(RED)
	{}
};


template <class T, class Ref, class Ptr>
struct __TreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef __TreeIterator<T, Ref, Ptr> Self;
	Node* _pnode;

	__TreeIterator(Node* pnode)
		:_pnode(pnode)
	{}

	Ref operator*()
	{
		return _pnode->_data;
	}

	Ptr operator->()
	{
		return &_pnode->_data;
	}
	
	Self& operator--()
	{
		
		if (_pnode->_left)//左子树不为空,下一节点为左子树的最右节点
		{
			Node* cur = _pnode->_left;
			while (cur->_right)
			{
				cur = cur->_right;
			}
			_pnode = cur;
		}
		else//左子树为空,找孩子是父亲右的那个祖先
		{
			Node* cur = _pnode;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_left)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_pnode = parent;
		}
		return *this;
	}
	
	Self& operator++()
	{
		if (_pnode->_right)
		{
			//右子树不为空,下一个节点为右子树的最左节点
			Node* cur = _pnode->_right;
			while (cur->_left)
			{
				cur = cur->_left;
			}
			_pnode = cur;
		}
		else
		{
			//右子树为空,下一个节点为节点为父亲左孩子的那个祖先
			Node* cur = _pnode;
			Node* parent = cur->_parent;
			while (parent && cur == parent->_right)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_pnode = parent;
		}
		return *this;
	}

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

template<class K, class T, class KeyOfT>//KeyOfT用来区分set和map
class RBTree
{
	typedef RBTreeNode<T> Node;

private:
	Node* _proot = nullptr;

public:
	typedef __TreeIterator<T, T&, T*> iterator;
	typedef __TreeIterator<T, const T&, const T*> const_iterator;
	iterator begin()
	{
		Node* cur = _proot;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return iterator(cur);
	}
	iterator end()
	{
		return iterator(nullptr);
	}

	const_iterator begin()const
	{
		Node* cur = _proot;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return const_iterator(cur);
	}
	const_iterator end()const
	{
		return const_iterator(nullptr);
	}

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

		Node* parent = nullptr;
		Node* cur = _proot;
		KeyOfT kot;

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

		//此时cur指向的位置就是新节点要插入的位置
		cur = new Node(data);
		Node* newnode = cur;
		cur->_col = RED;
		if (kot(data) < kot(parent->_data))
		{
			parent->_left = cur;
			cur->_parent = parent;
		}
		else
		{
			parent->_right = cur;
			cur->_parent = parent;
		}

		//插入结束,开始调整
		//父节点为黑色,不用调整
		while (parent && parent->_col == RED)
		{
			Node* grandfather = parent->_parent;//父节点为红色,必有祖父节点
			if (parent == grandfather->_left)
			{
				//		g
				//	p		u
				//c
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED)//情况1
				{
					uncle->_col = BLACK;
					parent->_col = BLACK;
					grandfather->_col = RED;
					//把g看作cur,继续向上更新
					cur = grandfather;
					parent = cur->_parent;
				}
				else//u不存在 或 u存在且为黑
				{
					if (cur == parent->_left)
					{
						//		g
						//	p
						//c
						//g右单旋
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;
					}
					else
					{
						//		g
						//	p
						//	 c
						//双旋:p左旋,然后g右旋
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
			else//p为g的右节点
			{
				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED)
				{
					parent->_col = BLACK;
					uncle->_col = BLACK;
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					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;
				}
			}
		}
		_proot->_col = BLACK;
		return make_pair(newnode, true);
	}

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

		if (cur == _proot) _proot = subL;

		if (parent)
		{
			if (parent->_left == cur)
				parent->_left = subL;
			else
				parent->_right = subL;
		}
	}

	void RotateL(Node* cur)
	{
		Node* subR = cur->_right;
		Node* subRL = subR->_left;
		cur->_right = subRL;
		if (subRL) subRL->_parent = cur;

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

		if (cur == _proot) _proot = subR;

		if (parent)
		{
			if (parent->_left == cur)
				parent->_left = subR;
			else
				parent->_right = subR;
		}
	}
	void InOrder()
	{
		_InOrder(_proot);
		cout << endl;
	}

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

		_InOrder(root->_left);
		cout << root->_data << " ";
		_InOrder(root->_right);
	}

	bool Check(Node* root, int blacknum, const int retVal)
	{
		if (root == nullptr)
		{
			if (blacknum != retVal)
			{
				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, retVal)
			&& Check(root->_right, blacknum, retVal);
	}

	bool IsBalance()
	{
		if (_proot == nullptr) return true;
		if (_proot->_col == RED) return false;

		int retVal = 0;
		Node* cur = _proot;
		while (cur)
		{
			if (cur->_col == BLACK) retVal++;
			cur = cur->_left;
		}

		int blacknum = 0;
		return Check(_proot, blacknum, retVal);
	}

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

		int LHeight = _Height(root->_left);
		int RHeight = _Height(root->_right);

		return LHeight > RHeight ? LHeight + 1 : RHeight + 1;
	}

	size_t Size()
	{
		return _Size(_proot);
	}
	size_t _Size(Node* root)
	{
		if (root == nullptr) return 0;

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

	Node* Find(const K& key)
	{
		Node* cur = _proot;
		while (cur)
		{
			if (cur->_data < key) cur = cur->_right;
			else if (cur->_data > key) cur = cur->_left;
			else return cur;
		}
		return nullptr;
	}

};

三、set、 map的模拟实现

set的模拟实现:

注意:为了防止修改迭代器指向的内容,set的iterator迭代器和const_iterator迭代器都设置成const_iterator迭代器。因此begin()和end()都是常量成员函数

#pragma once
#include "RBTree.h"

namespace zzx
{
	template<class K>
	class set
	{
	public:
		struct SetKeyOfT
		{
			const K& operator()(const K& key)
			{
				return key;
			}
		};

		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)
		{
			return _t.Insert(key);
		}

	private:
		RBTree<K, K, SetKeyOfT> _t;
	};


}

map的模拟实现:
注:为防止通过迭代器修改key,声明成员变量 _t 为RBTree<K, pair<const K, V>, MapKeyOfT>,对pair中的K用 const 修饰。

#pragma once
#include "RBTree.h"

namespace zzx
{
	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<const K, V>, MapKeyOfT>::iterator iterator;
		typedef typename RBTree<K, pair<const K, V>, MapKeyOfT>::const_iterator const_iterator;

		iterator begin()
		{
			return _t.begin();
		}

		iterator end()
		{
			return _t.end();
		}

		const_iterator end()const
		{
			return _t.end();
		}
		V& operator[](const K& key)
		{
			pair<iterator, bool> ret = insert(make_pair(key, V()));
			return ret.first->second;
		}

		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return _t.Insert(kv);
		}
	private:
		RBTree<K, pair<const K, V>, MapKeyOfT> _t;
	};
}
  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
红黑树是一种自平衡的二叉查找树,它在插入和删除节点时能够保持树的平衡。红黑树的概念可以参考。在Java中实现红黑树,可以按照以下步骤进行: 1. 首先将红黑树当作一颗二叉查找树,将新节点插入到适当的位置上。 2. 将插入的节点着色为"红色"。 3. 根据红黑树的特性,通过一系列的旋转和着色等操作,使树重新保持红黑树的性质。 具体的插入过程可以参考中提供的代码。在代码中,使用了左旋转、右旋转和颜色翻转等操作来重新平衡红黑树。 首先,如果节点的右子树是红色而左子树是黑色,可以通过左旋转操作将其变为左子树为红色,右子树为黑色的情况。 其次,如果节点的左子树和左子树的左子树都是红色,可以通过右旋转操作将其修正为上述情况。 最后,如果节点的左子树和右子树都是红色,可以通过颜色翻转操作将其修正为左子树和右子树都为黑色的情况。 在插入完节点后,需要将根节点的颜色设置为黑色,以确保红黑树的性质满足。 这样,通过以上的步骤,就能够实现对红黑树的插入操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java数据结构红黑树的真正理解](https://download.csdn.net/download/weixin_38622475/12770272)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Java高阶数据结构红黑树](https://blog.csdn.net/qq15035899256/article/details/126678970)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java数据结构——红黑树](https://blog.csdn.net/weixin_30699463/article/details/95256212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值