演算法與資料結構——AVL樹(平衡二叉樹)
阿新 • • 發佈:2020-10-27
定義
typedef struct AVLNode* Position;
typedef Position AVLTree; /* AVL樹型別 */
struct AVLNode {
ElementType Data; /* 結點資料 */
AVLTree Left; /* 指向左子樹 */
AVLTree Right; /* 指向右子樹 */
int Height; /* 樹高 */
};
前期準備函式
int Max(int a, int b) { return a > b ? a : b; } int GetHeight(Position T) { int hr, hl; if (!T) { return 0; } hl = GetHeight(T->Left); hr = GetHeight(T->Right); return (hl > hr) ? ++hl : ++hr; }
實現功能的主要函式
調整函式
Position SingleRoateWithLeft(Position A) { Position B; 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), GetHeight(B->Right)) + 1; return B;//new node } //右單旋 Position SingleRoateWithRight(Position A) { Position B; 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->Left), GetHeight(B->Right)) + 1; return B; } //右左雙旋 Position DoubleRoateWithLeft(Position A) { A->Left = SingleRoateWithRight(A->Left); return SingleRoateWithLeft(A); } //左右雙旋 Position DoubleRoateWithRight(Position A) { A->Right = SingleRoateWithLeft(A->Right); return SingleRoateWithRight(A); }
插入函式(兼具建樹功能)
AVLTree Insert(ElementType X, AVLTree T) { if (T == NULL) { T = new AVLNode; T->Data = X; T->Left = T->Right = NULL; T->Height = 0; } else if (X < T->Data) { T->Left = Insert(X, T->Left); if (GetHeight(T->Left) - GetHeight(T->Right) == 2) { if (X < T->Left->Data) { T = SingleRoateWithLeft(T); } else { T = DoubleRoateWithLeft(T); } } } else { T->Right = Insert(X, T->Right); if (GetHeight(T->Right) - GetHeight(T->Left) == 2) { if (X > T->Right->Data) { T = SingleRoateWithRight(T); } else { T = DoubleRoateWithRight(T); } } } T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1; return T; }
其他函式
VLTree MakeEmpty(AVLTree T)
{
if (T != NULL)
{
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free(T);
}
return NULL;
}
Position Find(ElementType X, AVLTree T)
{
if (T == NULL)
{
return NULL;
}
if (X < T->Data)
{
return Find(X,T->Left);
}
else if(X>T->Data)
{
return Find(X, T->Right);
}
else
{
return T;
}
}
Position FindMin(AVLTree T)
{
if (T == NULL)
{
return NULL;
}
else if(T->Left==NULL)
{
return T;
}
else
{
return FindMin(T->Left);
}
}
Position FindMax(AVLTree T)
{
if (T == NULL)
{
return NULL;
}
else if(T->Right==NULL)
{
return T;
}
else
{
return FindMax(T->Right);
}
}
深度和高度
void showHeight(int a,Position T)
{
if (T == NULL)
{
return;
}
showHeight(a,T->Left);
cout << T->Height << ' ';
showHeight(a,T->Right);
}
void showdeep(int depth,Position T)
{
if (T == NULL) return;
if (T)
{
showdeep(depth + 1, T->Left);
cout << depth+1<<' ';
showdeep(depth + 1, T->Right);
}
}