C++进阶AVL树

Posted Huang_ZhenSheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++进阶AVL树相关的知识,希望对你有一定的参考价值。

目录

右单旋:

左单旋:

左右双旋:

双旋平衡因子更新问题:

AVLTree完整代码:Gitee

右单旋:

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

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

		Node*ppNode = parent->_parent;

		subL->_right = parent;
		parent->_parent = subL;
        //这里要考虑subL的parent
		if (parent == _root)
		
			_root = subL;
			subL->_parent = nullptr;
		
		else
		
			if (ppNode->_left == parent)
				ppNode->_left = subL;
			else
				ppNode->_right = subL;

            subL->_parent = ppNode;
		
		parent->_bf = subL->_bf = 0;
	

左单旋:

void RotateL(Node* parent)//左旋
	
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		parent->_right = subRL;

		if (subRL)
		
			subRL->_parent = parent;
		
		Node* ppNode = parent->_parent;

		subR->_left = 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;
		
		parent->_bf = subR->_bf = 0;
	

左右双旋:

先左旋再右旋:先以30为旋转点,进行左单旋,再以90作为旋转点进行右单旋

先右旋再左旋:先以90为旋转点,进行右单旋,再以60作为旋转点进行左单旋

void RotateLR(Node* parent)
	
		RotateL(parent->_left);
		RotateR(parent);
	
	void RotateRL(Node* parent)
	
		RotateRL(parent->_right);
		RotateL(parent);
	

双旋平衡因子更新问题:

情况1:b插入,b的高度变成h

情况2:c插入,c的高度变成h

情况1和情况2如上图所画

情况3:

 60自己就是新增,bf = 0;

void RotateLR(Node* parent)
	
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		int bf = subLR->_bf;

		if (bf == -1)
		
			subL->_bf = 0;
			parent->_bf = 1;
			subLR->_bf = 0;
		
		else if (bf == 1)
		
			parent->_bf = 0;
			subL->_bf = -1;
			subLR -> _bf = 0;
		
		else if (bf == 0)
		
			parent->_bf = 0;
			subL->_bf = 0;
			subLR->_bf = 0;
		
		else
		
			assert(false);
		
		RotateL(parent->_left);
		RotateR(parent);
	
	void RotateRL(Node* parent)
	
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		int bf = subRL->_bf;

		RotateR(parent->_right);
		RotateL(parent);

		if (bf == 1)
		
			parent->_bf = -1;
			subR->_bf = 0;
			subRL->_bf = 0;
		
		else if (bf == -1)
		
			parent->_bf = 0;
			subR->_bf = 1;
			subRL->_bf = 0;
		
		else if (bf == 0)
		
			parent->_bf = 0;
			subR->_bf = 0;
			subRL->_bf = 0;
		
		else
		
			assert(false);
		
	

AVLTree完整代码:Gitee

以上是关于C++进阶AVL树的主要内容,如果未能解决你的问题,请参考以下文章

C++进阶数据结构_AVL树

C++进阶AVL树

C++进阶AVL树

C++进阶第十八篇——AVL树(概念+平衡因子的调节+旋转+代码实现)

C++ 树进阶系列之平衡二叉查找树( AVL)的自平衡算法

红黑树特性和实现详解——C++进阶数据结构