AVL树

一、定义
AVL树即高度平衡二叉搜索树,这里的高度指树的高度。
需要引入一个新的概念——平衡因子,一个节点的平衡因子等于其右子树高度-左子树高度的值。
AVL树的各节点的平衡因子只能属于0、-1、1三种情况。

二、结构
AVL树的实现需要使用三叉链,除了定义_left、_right外,还需要定义_parent,用于记录节点的父亲节点。同时平衡因子定义为int _bf。

三、节点插入对_bf的影响
分两种情况,其一,cur插入到parent的左边,parent的_bf--;其二,cur插入到parent的右边,parent的_bf++。

四、_bf更新后的处理
1.parent更新后的_bf==0的话,说明parent子树的高度没有发生变化,不再继续往上更新_bf。
2.parent更新后的|_bf|==1时,说明parent子树的高度发生变化,需要继续往上更新_bf。
3.parent更新后的|_bf|==2时,说明子树已经不平衡,不再更新_bf,需要旋转以求平衡。

五、旋转
1.左单旋

2.右单旋

3.右左双旋

4.左右双旋


六、需要旋转的情况
1.parent->_bf==2&&cur->_bf==1    需要进行左单旋

2.parent->_bf==-2&&cur->_bf==-1    需要进行右单旋

3.parent->_bf==2&&cur->_bf==-1    需要进行右左双旋

4.parent->_bf==-2&&cur->_bf==1    需要进行左右双旋


七、代码
以左单旋为例:

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 (_root == parent)     //判断parent的上面是否还有节点,并做出处理
       {
              _root = subR;
              subR->_parent = NULL;
       }
       else
       {
              if (ppNode->_right == parent)
              {
                     ppNode->_right = subR;
              }
              else
              {
                     ppNode->_left = subR;
              }
              subR->_parent = ppNode;
       }
}
八、完整代码
#pragma once  
template<class K,class V>
struct AVLTreeNode
{
	AVLTreeNode<K, V>* _left;
	AVLTreeNode<K, V>* _right;
	AVLTreeNode<K, V>* _parent;
	K _key;
	V _value;
	int _bf;  //平衡因子

	AVLTreeNode(const K& key, const V& value)   //构造函数
		:_key(key)
		, _value(value)
		, _left(NULL)
		, _right(NULL)
		, _parent(NULL)
		, _bf(0)
	{}
};

template<class K,class V>
class AVLTree
{
	typedef AVLTreeNode<K, V> Node;
public:
	AVLTree()
		:_root(NULL)
	{}

	bool Insert(const K& key, const V& value)
	{
		if (_root == NULL)
		{
			_root = new Node(key, value);
			return true;
		}
		Node* cur = _root;
		Node* parent = NULL;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key>key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key, value);
		if (parent->_key < key)
		{
			parent->_right = cur;
			cur->_parent = parent;
		}
		else
		{
			parent->_left = cur;
			cur->_parent = parent;
		}
		//更新平衡因子
		//如果不平衡,进行旋转
		while (parent)  //parent_bf==0时不需要更新,所以当parent不为0时更新
		{
			if (cur == parent->_right)
			{
				parent->_bf++;
			}
			else
			{
				parent->_bf--;
			}
			if (parent->_bf == 1 || parent->_bf == -1)  //直接向上更新
			{
				cur = parent;
				parent = cur->_parent;
			}
			else
			{
				//旋转以求平衡
				if (parent->_bf == -2)
				{
					if (cur->_bf == -1)   //右单旋
					{
						RotateR(parent);
					}
					else   //cur->_bf==1
					{
						RotateLR(parent);
					}
				}
				else if(parent->_bf==2)
				{
					if (cur->_bf == 1)   //左单旋
					{
						RotateL(parent);
					}
					else  //cur->_bf==-1
					{
						RotateRL(parent);
					}
				}
				break;  //旋转后平衡,直接break
			}  //end旋转
		} //end平衡因子的更新和失衡处理
		return true;
	}

	void RotateR(Node* parent)  //右单旋
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		//将subLR链到parent的左边
		parent->_left = subLR; 
		if (subLR)
		{
			subLR->_parent = parent;
		}
		//将parent链到subL的右边,并记录下原始parent的parent
		subL->_right = parent;
		Node* ppNode = parent->_parent;
		parent->_parent = subL;
		//判断parent之前是不是根节点,并由此给出相应处理
		if (ppNode == NULL)   //parent是根节点,或parent等于_root
		{
			_root = subL;
			subL->_parent = NULL;
		}
		else   //parent不是根节点
		{
			if (ppNode->_left == parent)
			{
				ppNode->_left = subL;
			}
			else
			{
				ppNode->_right = subL;
			}
			subL->_parent = ppNode;
		}
		subL->_bf = parent->_bf = 0;
	}

	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 (_root == parent)     //判断parent的上面是否还有节点,并做出处理
		{
			_root = subR;
			subR->_parent = NULL;
		}
		else
		{
			if (ppNode->_right == parent)
			{
				ppNode->_right = subR;
			}
			else
			{
				ppNode->_left = subR;
			}
			subR->_parent = ppNode;
		}
		subR->_bf = parent->_bf = 0;
	}

	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;
		}
		else if (bf == -1)
		{
			parent->_bf = 0;
			subR->_bf = 1;
		}
		else  //bf==0
		{
			subR->_bf = parent->_bf = 0;
		}
		subRL->_bf = 0;
	}

	void RotateLR(Node* parent)  //左右双旋
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		int bf = subLR->_bf;
		RotateL(parent->_left);
		RotateR(parent);
		if (bf == -1)
		{
			parent->_bf = 1;
			subL->_bf = 0;
		}
		else if (bf == 1)
		{
			parent->_bf = 0;
			subL->_bf = -1;
		}
		else
		{
			subL->_bf = parent->_bf = 0;
		}
		subLR->_bf = 0;
	}

	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

	void _InOrder(Node* root)
	{
		if (root == NULL)
		{
			return;
		}
		_InOrder(root->_left);
		cout << root->_key << " ";
		_InOrder(root->_right);
	}

	bool IsBlance()   //为了便于测试程序,设置检查平衡因子的函数
	{
		return _IsBlance(_root);
	}

	bool _IsBlance(Node* root)
	{
		if (root == NULL)
		{
			return true;
		}
		int left = Height(root->_left);
		int right = Height(root->_right);
		if ((right - left) != root->_bf ||( abs(right - left) >= 2))   //abs取绝对值
		{
			cout << "平衡因子异常" << root->_key << endl;
			return false;
		}
		return _IsBlance(root->_left) && _IsBlance(root->_right);
	}

	int Height(Node* root)
	{
		if (root == NULL)
		{
			return 0;
		}
		int left = Height(root->_left);
		int right = Height(root->_right);
		return left > right ? left + 1 : right + 1;
	}

protected:
	Node* _root;
};

void TestAVLTree()
{
	AVLTree<int, int> t;
	int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
	for (size_t i = 0; i < sizeof(a) / sizeof(a[0]); i++)
	{
		t.Insert(a[i], i);
	}
	t.InOrder();
	cout << "是否平衡? " << t.IsBlance() << endl;

	AVLTree<int, int> t1;
	int a1[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
	for (size_t i = 0; i < sizeof(a1) / sizeof(a1[0]); i++)
	{
		t1.Insert(a1[i], i);
	}
	t1.InOrder();
	cout << "是否平衡? " << t1.IsBlance() << endl;
}





07-07
AVL是一种自平衡的二叉查找,它确保了的高度始终保持在对数级别,从而保证了查找、插入和删除操作的时间复杂度为O(log n)。这种数据结构以它的发明者G.M. Adelson-Velsky和E.M. Landis的名字命名[^1]。 ### AVL的定义 - **平衡因子**:每个节点都有一个平衡因子,它是该节点左子的高度减去右子的高度。对于AVL来说,所有节点的平衡因子只能是-1, 0或1。 - **空**:如果T是空,则它自然是一个AVL。 - **非空**:若T不是空,则其左右子TL和TR都必须是AVL,并且对于任意节点,|HL - HR| ≤ 1(其中HL和HR分别表示左子和右子的高度)。 ### AVL的操作 当进行插入或删除操作时,可能会破坏AVL的平衡性,这时需要通过旋转来重新恢复平衡: - **单旋转**: - 左单旋(Single Rotate with Left)用于处理左孩子的左子过高。 - 右单旋(Single Rotate with Right)用于处理右孩子的右子过高。 - **双旋转**: - 左右双旋(Double Rotate with Left)用于处理左孩子的右子过高的情况。 - 右左双旋(Double Rotate with Right)用于处理右孩子的左子过高的情况。 这些旋转操作可以保持AVL的性质不变,并且能够快速地调整的结构以维持平衡。 ### AVL的实现 下面是一个简单的C语言代码示例,展示了如何定义AVL的节点以及实现基本的插入操作。这个例子中包含了必要的函数声明和一些核心逻辑。 ```c #include <stdio.h> #include <stdlib.h> // 定义AVL节点结构体 typedef struct AvlNode { int element; struct AvlNode *left; struct AvlNode *right; int height; // 节点的高度 } *AvlTree, *Position; // 获取两个整数中的较大者 int max(int a, int b) { return (a > b) ? a : b; } // 计算给定节点的高度 static int Height(AvlTree T) { if (T == NULL) return -1; // 空节点高度为-1 else return T->height; } // 单旋转 - 左左情况 AvlTree singlerotatewithLeft(AvlTree K2) { Position K1 = K2->left; K2->left = K1->right; K1->right = K2; // 更新节点高度 K2->height = max(Height(K2->left), Height(K2->right)) + 1; K1->height = max(Height(K1->left), K2->height) + 1; return K1; // 新根 } // 单旋转 - 右右情况 AvlTree singlerotatewithRight(AvlTree K2) { Position K1 = K2->right; K2->right = K1->left; K1->left = K2; // 更新节点高度 K2->height = max(Height(K2->left), Height(K2->right)) + 1; K1->height = max(Height(K1->right), K2->height) + 1; return K1; // 新根 } // 双旋转 - 左右情况 AvlTree doublerotatewithLeft(AvlTree K3) { K3->left = singlerotatewithRight(K3->left); return singlerotatewithLeft(K3); } // 双旋转 - 右左情况 AvlTree doublerotatewithRight(AvlTree K3) { K3->right = singlerotatewithLeft(K3->right); return singlerotatewithRight(K3); } // 插入新元素到AVLAvlTree Insert(int x, AvlTree T) { if (T == NULL) { // 如果为空,创建新节点 T = (AvlTree)malloc(sizeof(struct AvlNode)); if (T == NULL) printf("Out of space!!!"); else { T->element = x; T->left = T->right = NULL; T->height = 0; // 新叶节点高度为0 } } else if (x < T->element) { // 向左子插入 T->left = Insert(x, T->left); // 检查并修复平衡 if (Height(T->left) - Height(T->right) == 2) { if (x < T->left->element) T = singlerotatewithLeft(T); // 左左旋转 else T = doublerotatewithLeft(T); // 左右旋转 } } else if (x > T->element) { // 向右子插入 T->right = Insert(x, T->right); // 检查并修复平衡 if (Height(T->right) - Height(T->left) == 2) { if (x > T->right->element) T = singlerotatewithRight(T); // 右右旋转 else T = doublerotatewithRight(T); // 右左旋转 } } // 更新高度 T->height = max(Height(T->left), Height(T->right)) + 1; return T; } ``` 上述代码提供了AVL的基本框架,包括节点定义、插入操作及必要的旋转方法。实际应用中可能还需要添加更多的功能,如删除节点、查找特定值等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值