一.左旋和右旋(以左旋为例)
(1)左旋情况一:newroot左孩子为空
(2)左旋情况二:newroot左孩子不为空
二.思路图
三.双旋转
代码实现:
typedef int KeyType;
typedef struct AVLNode
{
struct AVLNode* leftchild;
struct AVLNode* parent;
struct AVLNode* rightchild;
int balance;//-1 0 1;
KeyType key;
}AVLNode;
typedef struct
{
AVLNode* root;
int cursize;
}AVLTree;
//左旋
static AVLNode* RotateLeft(AVLTree* ptree, AVLNode* ptr)
{
AVLNode* newroot = ptr->rightchild;//旋转点1.1
newroot->parent = ptr->parent;//修改旋转点父节点2.1
ptr->rightchild = newroot->leftchild;//1.2
if (newroot->leftchild != NULL)
{
newroot->leftchild->parent = ptr;//2.2
}
newroot->leftchild = ptr;//1.3
if (ptr == ptree->root)
{
ptree->root = newroot;
}
else
{
if (ptr == ptr->parent->leftchild)
{
ptr->parent->leftchild = newroot;
}
else
{
ptr->parent->rightchild = newroot;
}
}
ptr->parent = newroot;//2.3
return newroot;
}
//右旋
static AVLNode* RotateRight(AVLTree* ptree, AVLNode* ptr)
{
AVLNode* newroot = ptr->leftchild;
newroot->parent = ptr->parent;
ptr->leftchild = newroot->rightchild;
if (newroot->rightchild != NULL)
{
newroot->rightchild->parent = ptr;
}
newroot->rightchild = ptr;
if (ptr == ptree->root)
{
ptree->root = newroot;
}
else
{
if (ptr->parent->leftchild == ptr)
{
ptr->parent->leftchild = newroot;
}
else
{
ptr->parent->rightchild = newroot;
}
}
ptr->parent = newroot;
return newroot;
}
四.左平衡和右平衡(以左平衡为例)
情况一(插入m节点,A,B平衡因子发生变化)
情况二(插入m节点,A,B,E平衡因子发生变化)
情况三(插入m节点,A,B,E平衡因子发生变化)
代码实现:
//左平衡
static void LeftBalance(AVLTree* ptree, AVLNode* ptr)
{
AVLNode* subleft = ptr->leftchild, * subright = NULL;
switch (subleft->balance)
{
case 0:
fprintf(stderr, "left balance\n");
break;
case -1:
ptr->balance = 0;
subleft->balance = 0;
RotateRight(ptree, ptr);
break;
case 1:
subright = subleft->rightchild;
switch (subright->balance)
{
case 0:
ptr->balance = 0;
subleft->balance = 0;
break;
case 1:
ptr->balance = 0;
subleft->balance = -1;
break;
case -1:
ptr->balance = 1;
subleft->balance = 0;
break;
}
subright->balance = 0;
RotateLeft(ptree, ptr->leftchild);
RotateRight(ptree, ptr);
break;
}
}
//右平衡
static void RightBalance(AVLTree* ptree, AVLNode* ptr)
{
AVLNode* subleft =NULL, * subright = ptr->rightchild;
switch (subright->balance)
{
case 0:
fprintf(stderr, "right balance\n");
break;
case 1:
ptr->balance = 0;
subright->balance = 0;
RotateLeft(ptree, ptr);
break;
case -1:
subleft = subright->leftchild;
switch (subleft->balance)
{
case 0:
ptr->balance = 0;
subright->balance = 0;
break;
case 1:
ptr->balance = -1;
subright->balance = 0;
break;
case -1:
ptr->balance = 0;
subright->balance = 1;
break;
}
subleft->balance = 0;
RotateRight(ptree, ptr->rightchild);
RotateLeft(ptree, ptr);
break;
}
}