#include <iostream>
using namespace std;
typedef struct AVLNode* Position;
typedef Position AVLTree;//AVL树类型
typedef int ElementType ;
typedef struct AVLNode {
ElementType Data;//结点数据
AVLTree Left;//指向左子树
AVLTree Right;//指向右子树
int Height;//树高
};
int Max(int a, int b) {
return a > b ? a : b;
}
int GetHeight(AVLTree BT) {
int HL, HR, MaxH;
if (BT) {
HL = GetHeight(BT->Left);
HR = GetHeight(BT->Right);
MaxH = HL > HR ? HL : HR;
return (MaxH + 1);
}
else return 0;
}
AVLTree Insert(AVLTree T, ElementType x) {
if (!T) {
T = new AVLNode;
T->Data = x;
T->Left = T->Right = NULL;
T->Height = 1;
}
else if (x > T->Data) {//插入右子树
T->Right = Insert(T->Right, x);
if (GetHeight(T->Left) - GetHeight(T->Right) == -2) {
if (x > T->Right->Data)T = SingleRightRotation(T);//右单旋
else T = DoubleRightLeftRotation(T);//右-左双旋
}
}
else if (x < T->Data) {
//插入左子树
T->Left = Insert(T->Left, x);
if (GetHeight(T->Left) - GetHeight(T->Right) == 2) {
if (x < T->Left->Data)T = SingleLeftRotation(T);//左单旋
else T = DoubleLeftRightRotation(T);//右-左双旋
}
}
T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1;
return T;
}
AVLTree SingleLeftRotation(AVLTree A){//左单旋
AVLTree B = A->Left;
A->Left = B->Right;
B->Right = A;
A->Height = Max(GetHeight(A->Left), GetHeight(A->Right))+1;
B->Height = Max(GetHeight(B->Left), A->Height) + 1;
return B;
}
AVLTree DoubleLeftRightRotation(AVLTree A){//左-右双旋
A->Left = SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}
AVLTree SingleRightRotation(AVLTree A)//右单旋
{
AVLTree B = A->Right;
A->Right = B->Left;
B->Left = A;
A->Height = Max(GetHeight(A->Left), GetHeight(A->Right)) + 1;
B->Height = Max(GetHeight(B->Right), A->Height) + 1;
return B;
}
AVLTree DoubleRightLeftRotation(AVLTree A) {//右-左双旋
A->Right = SingleLeftRotation(A->Right);
return SingleRightRotation(A);
}
平衡二叉树(c++实现)
最新推荐文章于 2024-06-12 10:00:23 发布