树形结构关联式容器的底层结构

底层结构

树形结构的关联式容器map/set/multimap/multiset的共同点是:其底层结构都是按照二叉搜索树来实现的。

一、二叉搜索树

  • 二叉搜索树的概念
    二叉搜索树又称二叉排序树,它或者是一颗空树,或者具有以下性质的二叉树:
    1)若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
    2)若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
    3)它的左右子树也分别为二叉树
    【二叉搜索树的中序遍历是有序的】
    在这里插入图片描述
    ( 如图所示,就是一颗简单的二叉搜索树,在图中会发现,二叉树中的最小值在二叉搜索树的最左侧,最大值在二叉搜素树的最右侧)

  • 二叉搜索树的操作
    a、二叉树节点的定义:

 struct BSTreeNode
{
	BSTreeNode(const T& data=T())
		:_pLeft(nullptr)
		,_pRight(nullptr)
		,_data(data)
	{}
	BSTreeNode<T>* _pLeft;
	BSTreeNode<T>* _pRight;
	T _data;
};

b、二叉树的查找
在这里插入图片描述
若根节点不为空:
如果根节点的data==查找的data,返回节点
如果根节点的data> 查找的data,在其左子树中查找
如果根节点的data< 查找的data,在其右子树中查找
否则,返回NULL

   Node* find(const T& data)
   {
		Node* cur = _pRoot;
		while (cur)
		{
			if (data == cur->_data)
				return cur;
			else if (data < cur->_data)
				cur = cur->_pLeft;
			else
				cur = cur->_pRight;
		}
		return nullptr;
	}

c、二叉树的插入
在这里插入图片描述
插入过程:
1、树为空,则直接插入
2、树不为空,按照二叉搜索树的性质查找插入位置,插入新节点

插入代码:

bool Insert(const T& data)
	{
		if (_pRoot == nullptr)
		{
			_pRoot = new Node(data);
			return true;
		}
		Node* cur = _pRoot;
		Node* Parent = nullptr;
		while (cur)
		{
			Parent = cur;
			if (data < cur->_data)
				cur = cur->_pLeft;
			else if (data > cur->_data)
				cur = cur->_pRight;
			else
				return false;
		}

		cur = new Node(data);
		if (data < Parent->_data)
			Parent->_pLeft = cur;
		else
			Parent->_pRight = cur;

		return true;
	}

d、二叉搜索树的删除
1)空树----->直接返回
2)非空
> 找待删除节点在二叉搜索树中的位置
a、要删除的节点无孩子节点
b、要删除的节点只有左孩子节点
c、要删除的节点只有右孩子节点
d、要删除的节点有左孩子、右孩子节点
>删除节点
a情况:直接删除
b情况:删除该节点使该节点的双亲节点指向被删除节点的左孩子
c情况:删除该节点使该节点的双亲节点指向被删除节点的右孩子
d情况:在该节点的右子树中找最大值 (在左子树中找最小值),用它的值填补到被删除节点中,再来处理该节点的删除问题

  bool Delete(const T& data)
	{
		if (nullptr = _pRoot)
		{
			return false;
		}
		// 找待删除节点在二叉搜索树中的位置
		// 并保存其双亲

		Node* cur = _pRoot;
		Node* pParent = nullptr;
		while (cur)
		{
			if (data == cur->_data)
				break;
			else if (data < cur->_data)
			{
				pParent = cur;
				cur = cur->_pLeft;
			}
			else
			{
				pParent = cur;
				cur = cur->_pRight;
			}
		}

		// 该节点不在二叉搜索树中
		if (cur == nullptr)
			return false;


		// 已经找到该该节点,删除
		// 只有右孩子 || 叶子节点
		if (nullptr == cur->_pLeft)
		{
			if (nullptr == pParent)
				_pRoot = cur->_pRight;
			else
			{
				if (cur == pParent->_pLeft)
				{
					pParent->_pLeft = cur->_pRight;
				}
				else
				{
					pParent->_pRight = cur->_pRight;
				}
			}
		}
		else if (nullptr == cur->_pRight)
		{
			// 只有左孩子
			if (nullptr == pParent)
				_pRoot = cur->_pLeft;
			else
			{
				if (cur == pParent->_pLeft)
				{
					pParent->_pLeft = cur->_pLeft;
				}
				else
				{
					pParent->_pRight = cur->_pLeft;
				}
			}
		}
		else
		{
			// 左右孩子均存在
			Node* pDelNode = cur->_pRight;
			pParent = cur;
			// 找替代节点:在右子树中找最小(最左)
			while (pDelNode->_pLeft)
			{
				pParent = pDelNode;
				pDelNode = pDelNode->_pLeft;
			}
			// 用替代节点中值域替换删除节点
			cur->_data = pDelNode->_data;

			if (pDelNode == pParent->_pLeft)
				pParent->_pLeft = pDelNode->_pRight;
			else
				pParent->_pRight = pDelNode;

			cur = pDelNode;
		}
		delete cur;
		return true;

	}
  • 二叉搜索树的实现
template<class T>
struct BSTreeNode
{
	BSTreeNode(const T& data=T())
		:_pLeft(nullptr)
		,_pRight(nullptr)
		,_data(data)
	{}
	BSTreeNode<T>* _pLeft;
	BSTreeNode<T>* _pRight;
	T _data;
};

template<class T>
class BSTree
{
	typedef BSTreeNode<T> Node;
public:
	BSTree()
		:_pRoot(nullptr)
	{}

	//查找
	Node* find(const T& data)
	{
		Node* cur = _pRoot;
		while (cur != NULL)
		{
			if (data < cur->_data)
			{
				cur = cur->_pLeft;
			}
			else if(data>cur->_data)
			{
				cur=cur->_pRight
			}
			else
			{
				return cur;
			}
		}
		return nullptr;
	}

	//插入
	bool Insert(const T& data)
	{
		// 空树---直接插入
		if (_pRoot == nullptr)
		{
			_pRoot = new Node(data);
		}
		// 非空--找待插入节点在二叉搜索树中的位置
		// 并保存其双亲节点
		Node* cur = _pRoot;
		Node*pParent = nullptr;
		while (cur)
		{
			pParent = cur;
			if (data < cur->_data)
			{
				cur = cur->_pLeft;
			}
			else if (data > cur->_data)
			{
				cur = cur->_pRight;
			}
			else
			{
				return false;
			}
		}

		// 插入元素
		cur = new Node(data);
		if (data < pParent->_data)
		{
			pParent->_pLeft = cur;
		}
		else
		{
			pParent->_pRight = cur;
		}

		return true;
	}

	//删除
	bool Delete(const T& data)
	{
		if (nullptr = _pRoot)
		{
			return false;
		}
		// 找待删除节点在二叉搜索树中的位置
		// 并保存其双亲

		Node* cur = _pRoot;
		Node* pParent = nullptr;
		while (cur)
		{
			if (data == cur->_data)
				break;
			else if (data < cur->_data)
			{
				pParent = cur;
				cur = cur->_pLeft;
			}
			else
			{
				pParent = cur;
				cur = cur->_pRight;
			}
		}

		// 该节点不在二叉搜索树中
		if (cur == nullptr)
			return false;


		// 已经找到该该节点,删除
		// 只有右孩子 || 叶子节点
		if (nullptr == cur->_pLeft)
		{
			if (nullptr == pParent)
				_pRoot = cur->_pRight;
			else
			{
				if (cur == pParent->_pLeft)
				{
					pParent->_pLeft = cur->_pRight;
				}
				else
				{
					pParent->_pRight = cur->_pRight;
				}
			}
		}
		else if (nullptr == cur->_pRight)
		{
			// 只有左孩子
			if (nullptr == pParent)
				_pRoot = cur->_pLeft;
			else
			{
				if (cur == pParent->_pLeft)
				{
					pParent->_pLeft = cur->_pLeft;
				}
				else
				{
					pParent->_pRight = cur->_pLeft;
				}
			}
		}
		else
		{
			// 左右孩子均存在
			Node* pDelNode = cur->_pRight;
			pParent = cur;
			// 找替代节点:在右子树中找最小(最左)
			while (pDelNode->_pLeft)
			{
				pParent = pDelNode;
				pDelNode = pDelNode->_pLeft;
			}
			// 用替代节点中值域替换删除节点
			cur->_data = pDelNode->_data;

			if (pDelNode == pParent->_pLeft)
				pParent->_pLeft = pDelNode->_pRight;
			else
				pParent->_pRight = pDelNode;

			cur = pDelNode;
		}
		delete cur;
		return true;

	}

	//最小值
	Node* leftMost()
	{
		if (nullptr == _pRoot)
			return nullptr;

		Node* cur = _pRoot;
		while (cur->_pLeft)
		{
			cur = cur->_pLeft;
		}
		return cur;
	}

	//最大值
	Node* rightMost()
	{
		if (nullptr == _pRoot)
			return nullptr;

		Node* cur = _pRoot;
		while (cur->_pRight)
		{
			cur = cur->_pRight;
		}

		return cur;
	}

	void InOrder()
	{
		_InOrder(_pRoot);
	}

private:
	//中序遍历
	void _InOrder(Node* pRoot)
	{
		if (pRoot)
		{
			_InOrder(pRoot->_pLeft);
			cout << pRoot->_data << " ";
			_InOrder(pRoot->_pRight);
		}
	}
private:
	Node* _pRoot;
};
  • 二叉搜索树的性能分析
    插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。
    对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的 深度的函数,即结点越深,则比较次数越多。
    但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:
    完全二叉树:
    在这里插入图片描述
    右单支
    在这里插入图片描述
    最优情况下,二叉搜索树为完全二叉树,其平均比较次数为:log2N
    最差情况下,二叉搜索树退化为单支树,其平均比较次数为:N

    问题:如果退化成单支树,二叉搜索树的性能就失去了。那能否进行改进,不论按照什么次序插入关键码, 都可以是二叉搜索树的性能佳?
    二叉搜索树虽然可以缩短查找的效率,但如果数据有序或接近有序二叉搜索树将退化为单支树,查找元素相当于在顺序表中搜索元素,效率低下。所以发明了一种解决上述问题的方法:像二叉搜索树中插入新节点后,如果能保证每个节点的左右子树高度之差的绝对值不超过1,即可降低树的高度,从而减少平均搜索长度。

二、AVL树

  • AVL树的概念
    1)它的左右子树都是AVL树
    2)左右子树高度之差(简称平衡因子)的绝对值不超过1(-1/0/1)
    在这里插入图片描述
    如果一颗二叉搜索树是高度平衡的,那他就是AVL树。如果它有n个节点,其高度可保持在O(log2n),搜索时间复杂度O(log2n)
  • AVL树节点的定义
 template<class T>
struct AVLTreeNode
{
	AVLTreeNode(const T& data=T())
		:_pLeft(nullptr)
		,_pRight(nullptr)
		,_pParent(nullptr)
		,_data(data)
		,_bf(0)
	{}

	AVLTreeNode<T>* _pLeft;//该节点的左孩子
	AVLTreeNode<T>* _pRight;//该节点的右孩子
	AVLTreeNode<T>* _pParent;//该节点的双亲
	T _data;
	int _bf;//该节点的平衡因子
};
  • AVL树的插入
    AVL树就是在二叉搜索树的基础上引入平衡因子,因此AVL树也可以看成是二叉搜索树。那么AVL树的插入可以分为以下两个过程:
    1)按照二叉搜索树的方式插入新节点
    2)调整节点的平衡因子
    pCur插入后,pParent的平衡因子一定需要调整,在插入之前,pParent 的平衡因子分为三种情况:-1,0, 1, 分以下两种情况:
    1、如果pCur插入到pParent的左侧,只需给pParent的平衡因子-1即可
    2、如果pCur插入到pParent的右侧,只需给pParent的平衡因子+1即可
    此时:pParent的平衡因子可能有三种情况:0,正负1, 正负2
    a、 如果pParent的平衡因子为0,说明插入之前pParent的平衡因子为正负1,插入后被调整成0,此时满 足AVL树的性质,插入成功
    b、 如果pParent的平衡因子为正负1,说明插入前pParent的平衡因子一定为0,插入后被更新成正负1, 此时以pParent为根的树的高度增加,需要继续向上更新
    c、 如果pParent的平衡因子为正负2,则pParent的平衡因子违反平衡树的性质,需要对其进行旋转处理
bool Insert(const T& data)
	{
		//一、先按照二叉搜索树的方式进行插入
		if (nullptr == _pRoot)
		{
			_pRoot = new Node(data);
			return true;
		}
		// 按照二叉搜索树特性:找待插入节点在树中的位置
		// 并保存其双亲
		Node* cur = _pRoot;
		Node* pParent = nullptr;
		while (cur)
		{
			pParent = cur;
			if (data < cur->_data)
				cur = cur->_pLeft;
			else if (data > cur->_data)
				cur = cur->_pRight;
			else
				return false;
		}

		// 插入新节点
		cur = new Node(data);
		if (data < pParent->_data)
			pParent->_pLeft = cur;
		else
			pParent->_pRight = cur;

		cur->_pParent = pParent;

       //调整节点的平衡因子
		while (pParent)
		{
			// 更新pParent的平衡因子

			if (cur == pParent->_pLeft)
				pParent->_bf--;
			else
				pParent->_bf++;

			if (0 == pParent->_bf)
				break;
			else if (-1 == pParent->_bf || 1 == pParent->_bf)
			{
				cur = pParent;
				pParent = cur->_pParent;
			}
			else
			{
				// pParent->_bf: 2 || -2
				// pParent的节点失去平衡
				if (2 == pParent->_bf)
				{
					// 右子树高-->最后必须左单旋
					if (1 == cur->_bf)
						RotateL(pParent);
					else
						RotateRL(pParent);
				}
				else
				{
					if (-1 == cur->_bf)
						RotateR(pParent);
					else
						RotateLR(pParent);
				}

				break;
			}
		}
		return true;
	}
  • AVL树的旋转
    如果在一棵原本就是平衡的AVL树中插入一个新节点,可能造成不平衡,此时要调整树的结构。AVL树的旋转分为四种:
    1、新节点插入较高左子树的左侧—左左:右单旋
    在这里插入图片描述
void RotateR(Node* pParent)
	{
		Node* pSubL = pParent->_pLeft;
		Node* pSubLR = pSubL->_pRight;

		// 改变pParent和pSubL孩子的指向
		pParent->_pLeft = pSubLR;
		if (pSubLR)
			pSubLR->_pParent = pParent;

		pSubL->_pRight = pParent;

		// 更新pParent和pSubL的双亲
		Node* pPParent = pParent->_pParent;
		pParent->_pParent = pSubL;
		pSubL->_pParent = pPParent;

		// 更新原pParent双亲的左||右指针域指向
		if (nullptr == pPParent)
		{
			_pRoot = pSubL;
		}
		else
		{
			if (pParent == pPParent->_pLeft)
				pPParent->_pLeft = pSubL;
			else
				pPParent->_pRight = pSubL;
		}

		pParent->_bf = pSubL->_bf = 0;
	}

2、新节点插入较高右子树的右侧—右右:左单旋
在这里插入图片描述

   void RotateL(Node* pParent)
	{
		Node* pSubR = pParent->_pRight;
		Node* pSubRL = pSubR->_pLeft;

		pParent->_pRight = pSubRL;
		if (pSubRL)
			pSubRL->_pParent = pParent;

		pSubR->_pLeft = pParent;
		Node* pPParent = pParent->_pParent;
		pParent->_pParent = pSubR;
		pSubR->_pParent = pPParent;

		if (nullptr == pPParent)
		{
			_pRoot = pSubR;
		}
		else
		{
			if (pParent == pPParent->_pLeft)
				pPParent->_pLeft = pSubR;
			else
				pPParent->_pRight = pSubR;
		}

		pParent->_bf = pSubR->_bf = 0;
	}

3、新节点插入较高左子树的右侧-----左右:先左单旋在右单旋
在这里插入图片描述

void RotateLR(Node* pParent)
	{
		Node* pSubL = pParent->_pLeft;
		Node* pSubLR = pSubL->_pRight;
		int bf = pSubLR->_bf;

		RotateL(pParent->_pLeft);
		RotateR(pParent);
		if (-1 == bf)
			pParent->_bf = 1;
		else if (1 == bf)
			pSubL->_bf = -1;
	}

4、 新节点插入较高右子树的左侧----右左:先右单旋再左单旋
在这里插入图片描述

void RotateRL(Node* pParent)
	{
		Node* pSubR = pParent->_pRight;
		Node* pSubRL = pSubR->_pLeft;
		int bf = pSubRL->_bf;

		RotateR(pParent->_pRight);
		RotateL(pParent);

		// 更新部分节点的平衡因子
		if (bf == -1)
			pSubR->_bf = 1;
		else if (bf == 1)
			pParent->_bf = -1;
	}

总结
假如以pParent为根的子树不平衡,即pParent的平衡因子为2或者-2,分以下情况考虑
1、pParent的平衡因子为2,说明pParent的右子树高,设pParent的右子树的根为pSubR
a、当pSubR的平衡因子为1时,执行左单旋
b、当pSubR的平衡因子为-1时,执行右左双旋
2、pParent的平衡因子为-2,说明pParent的左子树高,设pParent的左子树的根为pSubL
a、当pSubL的平衡因子为-1是,执行右单旋
b、当pSubL的平衡因子为1时,执行左右双旋
旋转完成后,原pParent为根的子树个高度降低,已经平衡,不需要再向上更新。

  • AVL树的验证
    AVL树是在二叉搜索树的基础上加入了平衡性的限制,因此要验证AVL树,可以分两步:
    1、 验证其为二叉搜索树
    如果中序遍历可得到一个有序的序列,就说明为二叉搜索树
    2、 验证其为平衡树
    每个节点子树高度差的绝对值不超过1(注意节点中如果没有平衡因子) 节点的平衡因子是否计算正确
	int _Height(Node* pRoot)
	{
		if (nullptr == pRoot)
			return 0;

		int leftHeight = _Height(pRoot->_pLeft);
		int rightHeight = _Height(pRoot->_pRight);

		return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
	} 
     bool _IsAVLTree(Node* pRoot)
	{
	  // 空树也是AVL树
		if (nullptr == pRoot)
			return true;
      // 计算pRoot节点的平衡因子:即pRoot左右子树的高度差 
		int leftHeight = _Height(pRoot->_pLeft);
		int rightHeight = _Height(pRoot->_pRight);
      // 如果计算出的平衡因子与pRoot的平衡因子不相等,或者     
      // pRoot平衡因子的绝对值超过1,则一定不是AVL树
		if (abs(rightHeight - leftHeight) > 1 || rightHeight - leftHeight != pRoot->_bf)
			return false;
       // pRoot的左和右如果都是AVL树,则该树一定是AVL树 
		return _IsAVLTree(pRoot->_pLeft) && _IsAVLTree(pRoot->_pRight);
	}
  • AVL树的性能
    AVL树是一棵绝对平衡的二叉搜索树,其要求每个节点的左右子树高度差的绝对值都不超过1,这样可以保证 查询时高效的时间复杂度,即 。但是如果要对AVL树做一些结构修改的操作,性能非常低下,比如: 插入时要维护其绝对平衡,旋转的次数比较多,更差的是在删除时,有可能一直要让旋转持续到根的位置。 因此:如果需要一种查询高效且有序的数据结构,而且数据的个数为静态的(即不会改变),可以考虑AVL树, 但一个结构经常修改,就不太适合
  • AVL树的实现
 //AVL树
template<class T>
struct AVLTreeNode
{
	AVLTreeNode(const T& data=T())
		:_pLeft(nullptr)
		,_pRight(nullptr)
		,_pParent(nullptr)
		,_data(data)
		,_bf(0)
	{}

	AVLTreeNode<T>* _pLeft;//该节点的左孩子
	AVLTreeNode<T>* _pRight;//该节点的右孩子
	AVLTreeNode<T>* _pParent;//该节点的双亲
	T _data;
	int _bf;//该节点的平衡因子
};


//AVL:二叉搜索树+平衡因子的限制
template<class  T>
class AVLTree
{
	typedef AVLTreeNode<T> Node;
public:
	AVLTree()
		:_pRoot(nullptr)
	{}

	bool Insert(const T& data)
	{
		//先按照二叉搜索树的方式进行插入
		if (nullptr == _pRoot)
		{
			_pRoot = new Node(data);
			return true;
		}
		// 按照二叉搜索树特性:找待插入节点在树中的位置
		// 并保存其双亲
		Node* cur = _pRoot;
		Node* pParent = nullptr;
		while (cur)
		{
			pParent = cur;
			if (data < cur->_data)
				cur = cur->_pLeft;
			else if (data > cur->_data)
				cur = cur->_pRight;
			else
				return false;
		}

		// 插入新节点
		cur = new Node(data);
		if (data < pParent->_data)
			pParent->_pLeft = cur;
		else
			pParent->_pRight = cur;

		cur->_pParent = pParent;

		while (pParent)
		{
			// 更新pParent的平衡因子

			if (cur == pParent->_pLeft)
				pParent->_bf--;
			else
				pParent->_bf++;

			if (0 == pParent->_bf)
				break;
			else if (-1 == pParent->_bf || 1 == pParent->_bf)
			{
				cur = pParent;
				pParent = cur->_pParent;
			}
			else
			{
				// pParent->_bf: 2 || -2
				// pParent的节点失去平衡
				if (2 == pParent->_bf)
				{
					// 右子树高-->最后必须左单旋
					if (1 == cur->_bf)
						RotateL(pParent);
					else
						RotateRL(pParent);
				}
				else
				{
					if (-1 == cur->_bf)
						RotateR(pParent);
					else
						RotateLR(pParent);
				}

				break;
			}
		}
		return true;
	}

	void InOrder()
	{
		_InOrder(_pRoot);
	}

	Node* LeftMost()
	{
		if (nullptr == _pRoot)
			return nullptr;

		Node* cur = _pRoot;
		while (cur->_pLeft)
		{
			cur = cur->_pLeft;
		}
		return cur;
	}

	Node* RightMost()
	{
		if (nullptr == _pRoot)
			return nullptr;

		Node* cur = _pRoot;
		while (cur->_pRight)
			cur = cur->_pRight;

		return cur;
	}

	bool IsAVLTree()
	{
		return _IsAVLTree(_pRoot);
	}
private:
	bool _IsAVLTree(Node* pRoot)
	{
		if (nullptr == pRoot)
			return true;

		int leftHeight = _Height(pRoot->_pLeft);
		int rightHeight = _Height(pRoot->_pRight);

		if (abs(rightHeight - leftHeight) > 1 || rightHeight - leftHeight != pRoot->_bf)
			return false;

		return _IsAVLTree(pRoot->_pLeft) && _IsAVLTree(pRoot->_pRight);
	}

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

		int leftHeight = _Height(pRoot->_pLeft);
		int rightHeight = _Height(pRoot->_pRight);

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

	void RotateR(Node* pParent)
	{
		Node* pSubL = pParent->_pLeft;
		Node* pSubLR = pSubL->_pRight;

		// 改变pParent和pSubL孩子的指向
		pParent->_pLeft = pSubLR;
		if (pSubLR)
			pSubLR->_pParent = pParent;

		pSubL->_pRight = pParent;

		// 更新pParent和pSubL的双亲
		Node* pPParent = pParent->_pParent;
		pParent->_pParent = pSubL;
		pSubL->_pParent = pPParent;

		// 更新原pParent双亲的左||右指针域指向
		if (nullptr == pPParent)
		{
			_pRoot = pSubL;
		}
		else
		{
			if (pParent == pPParent->_pLeft)
				pPParent->_pLeft = pSubL;
			else
				pPParent->_pRight = pSubL;
		}

		pParent->_bf = pSubL->_bf = 0;
	}

	void RotateL(Node* pParent)
	{
		Node* pSubR = pParent->_pRight;
		Node* pSubRL = pSubR->_pLeft;

		pParent->_pRight = pSubRL;
		if (pSubRL)
			pSubRL->_pParent = pParent;

		pSubR->_pLeft = pParent;
		Node* pPParent = pParent->_pParent;
		pParent->_pParent = pSubR;
		pSubR->_pParent = pPParent;

		if (nullptr == pPParent)
		{
			_pRoot = pSubR;
		}
		else
		{
			if (pParent == pPParent->_pLeft)
				pPParent->_pLeft = pSubR;
			else
				pPParent->_pRight = pSubR;
		}

		pParent->_bf = pSubR->_bf = 0;
	}

	void RotateRL(Node* pParent)
	{
		Node* pSubR = pParent->_pRight;
		Node* pSubRL = pSubR->_pLeft;
		int bf = pSubRL->_bf;

		RotateR(pParent->_pRight);
		RotateL(pParent);

		// 更新部分节点的平衡因子
		if (bf == -1)
			pSubR->_bf = 1;
		else if (bf == 1)
			pParent->_bf = -1;
	}

	void RotateLR(Node* pParent)
	{
		Node* pSubL = pParent->_pLeft;
		Node* pSubLR = pSubL->_pRight;
		int bf = pSubLR->_bf;

		RotateL(pParent->_pLeft);
		RotateR(pParent);
		if (-1 == bf)
			pParent->_bf = 1;
		else if (1 == bf)
			pSubL->_bf = -1;
	}

	void _InOrder(Node* pRoot)
	{
		if (pRoot)
		{
			_InOrder(pRoot->_pLeft);
			cout << pRoot->_data << " ";
			_InOrder(pRoot->_pRight);
		}
	}
private:
	Node* _pRoot;
};

三、红黑树

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

  • 红黑树的性质
    1)每个节点不是红色就是黑色
    2)根节点一定为黑色
    3)如果一个节点是红色的,它的孩子节点一定是黑色
    4)每条路径中的黑色节点的个数相同
    5)每个叶子节点都是黑色(此处的叶子节点指的是空节点)
    结论:最长路径中的节点个数不会超过最短路径节点个数的两倍。
    因此:红黑树是一颗近似平衡的二叉搜索树,红黑树性能比AVL树更佳,而且实现比较简单
    在这里插入图片描述

  • 红黑树节点的定义:

 //节点的颜色
enum Color{RED,BLACK};

template<class T>
struct RBTreeNode
{
	RBTreeNode(const T& data=T(),Color color=RED)
		:_pLeft(nullptr)
		,_pRight(nullptr)
		,_pParent(nullptr)
		,_data(data)
		,_color(color)
	{}

	RBTreeNode<T>* _pLeft;//节点的左孩子
	RBTreeNode<T>* _pRight;//节点的右孩子
	RBTreeNode<T>* _pParent;//节点的双亲
	T _data;//节点的值域
	Color _color;//节点的颜色

};
  • 红黑树的结构
    为了实现关联式容器简单,红黑树的实现增加一个头结点,因为跟节点必须为黑色,为了与根节点进行区分,将头结点给成红色,并且让头结点的pParent域指向红黑树的根节点pLeft指向红黑树中最小的节点(最左侧节点),_pRight指向红黑树最大的节点(最右侧节点)
    在这里插入图片描述
 template<class T>
class RBTree
{
	typedef RBTreeNode<T> Node;
public:
	RBTree()
	{
		_pHead->_pParent = nullptr;
		_pHead->_pLeft = _pHead;
		_pHead->_pRight = _pHead;
	}

	Node*& GetRoot()
	{
		return _pHead->_pParent;
	}
private:
	Node* _pHead;
};
  • 红黑树的插入操作
    红黑树是在二叉搜索树的基础上加上其平衡限制条件,因此红黑树的插入可分为两步:
    1、按照二叉搜索树的规则插入新节点
    2、检测新节点插入后,红黑树的性质是否遭到破坏
    因为新节点默认颜色是红色,因此:如果其双亲节点的颜色是黑色,没有违反性质三不能有连在一起的红色节点,此时需要对红黑树分情况来讨论:
    约定:cur为当前节点,p为父节点,g为祖父节点,u为叔叔节点
    a、cur为红,p为红,g为黑,u存在且为红
    在这里插入图片描述
    cur和p均为红,违反了性质三
    解决方式:将p,u改为黑色,g改为红,然后把g当成cur,继续向上调整。
    b、cur为红,p为红,g为黑,u不存在/u为黑
    在这里插入图片描述
    p为g的左孩子,cur为p的左孩子,则进行右单旋转;
    相反, p为g的右孩子,cur为p的右孩子,则进行左单旋转
    p、g变色–p变黑,g变红
    c、 cur为红,p为红,g为黑,u不存在/u为黑
    在这里插入图片描述
    p为g的左孩子,cur为p的右孩子,则针对p做左单旋转;
    相反, p为g的右孩子,cur为p的左孩子,则针对p做右单旋转
    则转换成了情况2
bool Insert(const T& data)
	{
		// 按照二叉搜索树的性质插入新节点
		Node*& pRoot = GetRoot();
		if (nullptr == pRoot)
		{
			pRoot = new Node(data, BLACK);
			pRoot->_pParent = _pHead;
			return true;
		}
		else
		{
			// 找待插入节点在二叉搜索树中的位置
			// 并保存其双亲节点
			Node* cur = pRoot;
			Node* pParent = nullptr;
			while (cur)
			{
				pParent = cur;
				if (data < cur->_data)
					cur = cur->_pLeft;
				else if (data > cur->_data)
					cur = cur->_pRight;
				else
					return false;
			}
			// 插入新节点
			cur = new Node(data);
			if (data < pParent->_data)
				pParent->_pLeft =cur;
			else
				pParent->_pRight = cur;

			cur->_pParent = pParent;

			//cur新节点的默认颜色:红色
			//如果pParent的颜色是黑色,满足红黑树的性质
			//如果pParent的颜色是红色,违反了性质三----不能有连在一起的红色节点
			while (pParent != _pHead && pParent->_color == RED)
			{
				Node* grandFather = pParent->_pParent;
				if (pParent == grandFather->_pLeft)
				{
					Node* uncle = grandFather->_pRight;
					if (uncle && uncle->_color == RED )
					{
						//情况一:
						pParent->_color = BLACK;
						uncle->_color = BLACK;
						grandFather->_color = RED;
						cur = grandFather;
						pParent = cur->_pParent;
					}
					else
					{
						//叔叔节点不存在||叔叔节点存在&&黑色
						if (cur == pParent->_pRight)
						{
							//情况三:
							RotateL(pParent);
							swap(cur, pParent);
						}

						pParent->_color = BLACK;
						grandFather->_color = RED;
						RotateR(grandFather);
					}
				}
				else
				{
					Node* uncle = grandFather->_pLeft;
					if (uncle&&RED == uncle->_color)
					{
						pParent->_color = BLACK;
						uncle->_color = BLACK;
						grandFather->_color = RED;
						cur = grandFather;
						pParent = cur->_pParent;
					}
					else
					{
						//叔叔节点不存在||存在且为黑
						if (cur == pParent->_pLeft)
						{
							RotateR(pParent);
							swap(cur, pParent);
						}
						pParent->_color = BLACK;
						grandFather->_color = RED;
						RotateL(grandFather);
					}
				}
			}
		}

		pRoot->_color = BLACK;
		_pHead->_pLeft = leftMost();
		_pHead->_pRight = rightMost();
		return true;
	}
  • 红黑树的验证
    红黑树的检测分为两步:
    1、检测其是否满足二叉搜索树(中序遍历是否为有序序列)
    2、检测其是否满足红黑树的性质
bool IsValidRBTree()
	{
		Node* pRoot = GetRoot();
		
		 // 空树也是红黑树
		if (nullptr == pRoot)
			return true;
      
         // 检测根节点是否满足情况
		if (pRoot->_color != BLACK)
		{
			cout << "违反性质二:根节点是黑色" << endl;
			return false;
		}

		//获取一条路径中黑色节点的个数
		size_t blackCount = 0;
		Node* cur = pRoot;
		while (cur)
		{
			if (cur->_color == BLACK)
				blackCount++;

			cur = cur->_pLeft;
		}
        // 检测是否满足红黑树的性质,pathBlack用来记录路径中黑色节点的个数
		size_t pathBlack = 0;
		return _IsValidRBTree(pRoot, blackCount, pathBlack);
	}


	bool _IsValidRBTree(Node* pRoot, size_t blackCount, size_t pathBlack)
	{
		if (nullptr == pRoot)
			return true;
        // 统计黑色节点的个数
		if (pRoot->_color == BLACK)
			pathBlack++;

		Node* pParent = pRoot->_pParent;
		if (pParent != _pHead && RED == pParent->_color&&RED == pRoot->_color)
		{
			cout << "违反性质3:不能存在连在一起的红色节点" << endl;
			return false;
		}

		//叶子节点
		if (nullptr == pRoot->_pLeft&&nullptr == pRoot->_pRight)
		{
			if (pathBlack != blackCount)
			{
				cout << "违反性质4:每条路径中黑色节点个数均相同" << endl;
				return false;
			}
		}
		
		return _IsValidRBTree(pRoot->_pLeft, blackCount, pathBlack) &&
			_IsValidRBTree(pRoot->_pRight, blackCount, pathBlack);
	}
  • 红黑树与AVL树的比较
    红黑树和AVL都是高效的平衡二叉树,增删改查的时间复杂度都是O( log2N),红黑树不追求绝对平衡,其只需要保证最长路径不超过最短路径的2倍,相对而言,降低了插入和旋转的次数,所以在经常进行增删的结构中性能比AVL树更优,而且红黑树实现比较简单,所以实际运用中红黑树更多。
  • 红黑树的实现
 //节点的颜色
enum Color{RED,BLACK};

template<class T>
struct RBTreeNode
{
	RBTreeNode(const T& data=T(),Color color=RED)
		:_pLeft(nullptr)
		,_pRight(nullptr)
		,_pParent(nullptr)
		,_data(data)
		,_color(color)
	{}

	RBTreeNode<T>* _pLeft;//节点的左孩子
	RBTreeNode<T>* _pRight;//节点的右孩子
	RBTreeNode<T>* _pParent;//节点的双亲
	T _data;//节点的值域
	Color _color;//节点的颜色

};


template<class T>
class RBTree
{
	typedef RBTreeNode<T> Node;
public:
	RBTree()
	{
		_pHead = new Node;
		_pHead->_pLeft = _pHead;
		_pHead->_pRight = _pHead;

	}

	bool Insert(const T& data)
	{
		// 按照二叉搜索树的性质插入新节点
		Node*& pRoot = GetRoot();
		if (nullptr == pRoot)
		{
			pRoot = new Node(data, BLACK);
			pRoot->_pParent = _pHead;
			return true;
		}
		else
		{
			// 找待插入节点在二叉搜索树中的位置
			// 并保存其双亲节点
			Node* cur = pRoot;
			Node* pParent = nullptr;
			while (cur)
			{
				pParent = cur;
				if (data < cur->_data)
					cur = cur->_pLeft;
				else if (data > cur->_data)
					cur = cur->_pRight;
				else
					return false;
			}
			// 插入新节点
			cur = new Node(data);
			if (data < pParent->_data)
				pParent->_pLeft =cur;
			else
				pParent->_pRight = cur;

			cur->_pParent = pParent;

			//cur新节点的默认颜色:红色
			//如果pParent的颜色是黑色,满足红黑树的性质
			//如果pParent的颜色是红色,违反了性质三----不能有连在一起的红色节点
			while (pParent != _pHead && pParent->_color == RED)
			{
				Node* grandFather = pParent->_pParent;
				if (pParent == grandFather->_pLeft)
				{
					Node* uncle = grandFather->_pRight;
					if (uncle && uncle->_color == RED )
					{
						//情况一:
						pParent->_color = BLACK;
						uncle->_color = BLACK;
						grandFather->_color = RED;
						cur = grandFather;
						pParent = cur->_pParent;
					}
					else
					{
						//叔叔节点不存在||叔叔节点存在&&黑色
						if (cur == pParent->_pRight)
						{
							//情况三:
							RotateL(pParent);
							swap(cur, pParent);
						}

						pParent->_color = BLACK;
						grandFather->_color = RED;
						RotateR(grandFather);
					}
				}
				else
				{
					Node* uncle = grandFather->_pLeft;
					if (uncle&&RED == uncle->_color)
					{
						pParent->_color = BLACK;
						uncle->_color = BLACK;
						grandFather->_color = RED;
						cur = grandFather;
						pParent = cur->_pParent;
					}
					else
					{
						//叔叔节点不存在||存在且为黑
						if (cur == pParent->_pLeft)
						{
							RotateR(pParent);
							swap(cur, pParent);
						}
						pParent->_color = BLACK;
						grandFather->_color = RED;
						RotateL(grandFather);
					}
				}
			}
		}

		pRoot->_color = BLACK;
		_pHead->_pLeft = leftMost();
		_pHead->_pRight = rightMost();
		return true;
	}


	Node*& GetRoot()
	{
		return _pHead->_pParent;
	}

	void InOrder()
	{
		_InOrder(GetRoot());
	}

	Node* leftMost()
	{
		Node* pRoot = GetRoot();
		if (nullptr == pRoot)
			return _pHead;

		Node* cur = pRoot;
		while (cur->_pLeft)
			cur = cur->_pLeft;

		return cur;
	}

	Node* rightMost()
	{
		Node* pRoot = GetRoot();
		if (nullptr == pRoot)
			return _pHead;

		Node* cur = pRoot;
		while (cur->_pRight)
			cur = cur->_pRight;

		return cur;
	}

	bool IsValidRBTree()
	{
		Node* pRoot = GetRoot();
		if (nullptr == pRoot)
			return true;

		if (pRoot->_color != BLACK)
		{
			cout << "违反性质一:根节点是黑色" << endl;
			return false;
		}

		//获取一条路径中黑色节点的个数
		size_t blackCount = 0;
		Node* cur = pRoot;
		while (cur)
		{
			if (cur->_color == BLACK)
				blackCount++;

			cur = cur->_pLeft;
		}

		size_t pathBlack = 0;
		return _IsValidRBTree(pRoot, blackCount, pathBlack);
	}

private:
	bool _IsValidRBTree(Node* pRoot, size_t blackCount, size_t pathBlack)
	{
		if (nullptr == pRoot)
			return true;

		if (pRoot->_color == BLACK)
			pathBlack++;

		Node* pParent = pRoot->_pParent;
		if (pParent != _pHead && RED == pParent->_color&&RED == pRoot->_color)
		{
			cout << "违反性质3:不能存在连在一起的红色节点" << endl;
			return false;
		}

		//叶子节点
		if (nullptr == pRoot->_pLeft&&nullptr == pRoot->_pRight)
		{
			if (pathBlack != blackCount)
			{
				cout << "违反性质4:每条路径中黑色节点个数均相同" << endl;
				return false;
			}
		}
		return _IsValidRBTree(pRoot->_pLeft, blackCount, pathBlack) &&
			_IsValidRBTree(pRoot->_pRight, blackCount, pathBlack);
	}


	void _InOrder(Node* pRoot)
	{
		if (pRoot)
		{
			_InOrder(pRoot->_pLeft);
			cout << pRoot->_data << " ";
			_InOrder(pRoot->_pRight);
		}
	}

	void RotateL(Node* pParent)
	{
		Node* pSubR = pParent->_pRight;
		Node* pSubRL = pSubR->_pLeft;

		pParent->_pRight = pSubRL;
		if (pSubRL)
			pSubRL->_pParent = pParent;

		pSubR->_pLeft = pParent;
		Node* ppParent = pParent->_pParent;

		pSubR->_pParent = ppParent;
		pParent->_pParent = pSubR;
		if (ppParent == nullptr)
		{
			_pHead->_pParent = pSubR;
		}
		else
		{
			if (pParent == ppParent->_pLeft)
				ppParent->_pLeft = pSubR;
			else
				ppParent->_pRight = pSubR;
		}

	}
	void RotateR(Node* pParent)
	{
		Node* pSubL = pParent->_pLeft;
		Node* pSubLR = pSubL->_pRight;

		pParent->_pLeft = pSubLR;
		if (pSubLR)
			pSubLR->_pParent = pParent;

		pSubL->_pRight = pParent;

		Node* pPParent = pParent->_pParent;
		pParent->_pParent = pSubL;
		pSubL->_pParent = pPParent;

		if (pPParent == _pHead)
			_pHead->_pParent = pSubL;
		else
		{
			if (pParent == pPParent->_pLeft)
				pPParent->_pLeft = pSubL;
			else
				pPParent->_pRight = pSubL;
		}
	}
private:
	Node* _pHead;
};
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值