原因
二叉搜索树虽可以缩短查找的效率,但如果数据有序或接近有序二叉搜索树将退化为单支树, 查找元素相当于在顺序表中搜索元素,效率低下。
因此,两位俄罗斯的数学家G.M.Adelson-Velskii和E.M.Landis在1962年发明了一种解决上述问 题的方法:当向二叉搜索树中插入新结点后,如果能保证每个结点的左右子树高度之差的绝 对值不超过1(需要对树中的结点进行调整),即可降低树的高度,从而减少平均搜索长度。
概念
一棵AVL树或者是空树,或者是具有以下性质的二叉搜索树:
1、它的左右子树都是AVL树
2、左子树和右子树高度之差(简称平衡因子)的绝对值不超过1(-1、0、1)
如果一棵二叉搜索树是高度平衡的,它就是AVL树。如果它有n个结点,其高度可保持在 O(lgn),平均搜索时间复杂度O(lg(n)).
AVL树的实现原理
通过旋转将不平衡的二叉树变得平衡。
如果在一棵原本是平衡的二叉搜索树中插入一个新节点,可能造成不平衡,此时必须调整树的 结构,使之平衡化。
左单旋
代码如下
void _RotateL(Node* pParent)/左旋 右右 :在较高右子树的右侧插入新节点
{
Node* pSubR = pParent->_pRight;
Node* pSubRL = pSubR->_pLeft;
Node* pPParent = pParent->_pParent;
pParent->_pRight = pSubRL;
if(pSubRL) //是否存在
{
pSubRL->_pParent = pParent;
pParent->_bf = 0;
}
else
pParent->_bf = -1;
pSubR->_pLeft = pParent;
pParent->_pParent = pSubR;
pSubR->_pParent = pPParent;
if (pParent == _pRoot) //若为根节点
_pRoot = pSubR;
else //为子树
{
if (pPParent->_pLeft == pParent)
pPParent->_pLeft = pSubR;
else
pPParent->_pRight = pSuR;
}
pSubR->_bf = 0;
pSubR->_bf = 0;
}
右旋
右旋与左旋称称
`void _RotateR(Node * pParent) /右旋 左左: 在较高左子树的左侧插入新节点
{
Node* pPParent = pParent->_pParent;
Node* pSubL = pParent->_pLeft;
Node* pSubLR = pSubL->_pRight;
pParent->_pLeft = pSubLR;
if (pSubLR)
{
pSubLR->_pParent = pParent;
pParent->_bf = 0 ;
}
else
pParent->_bf = 1;
pSubL->_pRight = pParent;
pParent->_pParent = pSubL;
pSubL->_pParent = pPParent;
if (pPParent == NULL)
_pRoot = pSubL;
else
{
if (pPParent->_pLeft == pParent)
pPParent->_pLeft = pSubL;
else
pPParent->_pRight = pSubL;
}
pSubL->_bf = 0;
}`
右左旋
插入点位于ptr右子节点的左子树–右左
void _RotateRL(Node* pParent) /右左旋 在较高右子树的左侧插入新节点
{
_RotateR(pParent->_pRight);
pParent->_pRight->_bf =1;
_RotateL(pParent);
}
在旋转完后一定要根据情况调整数的平衡因子
## 删除 ##
删除后也要更新平衡因子和旋转