1. 程式人生 > 其它 >平衡二叉樹的根

平衡二叉樹的根

這應該是一道典型考察的平衡二叉樹的操作的題目。

---------------------------------------------------------------------------------------------------------

練習4.2 平衡二叉樹的根 (25 分)

將給定的一系列數字插入初始為空的AVL樹,請你輸出最後生成的AVL樹的根結點的值。

輸入格式:

輸入的第一行給出一個正整數N(20),隨後一行給出N個不同的整數,其間以空格分隔。

輸出格式:

在一行中輸出順序插入上述整數到一棵初始為空的AVL樹後,該樹的根結點的值。

輸入樣例1:

5
88 70 61 96 120
結尾無空行

輸出樣例1:

70
結尾無空行

輸入樣例2:

7
88 70 61 96 120 90 65

輸出樣例2:

88



--------------------------------------------------------------------------------------

接下來是開始解題思路,
好吧好像也沒什麼解題思路,這不是很明顯是就課本上的程式碼嗎。

#include <stdio.h>
#include <stdlib.h>

typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
int Data;
AVLTree Left;
AVLTree Right;
int Height;
};

int Max(int a,int b)
{
return (a>b? a:b);
}

int GetHeight(AVLTree T)
{
if(!T)
{
return 0;
}
return Max(GetHeight(T->Left),GetHeight(T->Right))+1;
}

AVLTree SignleLeftRotation(AVLTree A)
{
// A必須有一個左子結點
//A和B做左單旋
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),GetHeight(B->Right))+1;

return B;
}

AVLTree SignleRightRotation(AVLTree A)
{
//A必須有一個右子結點
//A和B做右單旋
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->Left),GetHeight(B->Right))+1;

return B;
}

AVLTree DoubleLeftRightRotation(AVLTree A)
{
//A必須有左結點B,且B必須有右結點
//A,B與C做兩次單旋,返回C
A->Left = SignleRightRotation(A->Left);
return SignleLeftRotation(A);
}

AVLTree DoubleRightLeftRotaion(AVLTree A)
{
A->Right = SignleLeftRotation(A->Right);
return SignleRightRotation(A);
}

AVLTree Insert(AVLTree T,int x)
{
if(!T)
{
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Data = x;
T->Height = 1;
T->Left = T->Right = NULL;
}
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 = SignleLeftRotation(T);
else
T = DoubleLeftRightRotation(T);
}
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 = SignleRightRotation(T);
else
T = DoubleRightLeftRotaion(T);
}
}
T->Height = Max(GetHeight(T->Left),GetHeight(T->Right))+1;

return T;
}

int main(void)
{
AVLTree T = NULL;
int N,x;
scanf("%d",&N);
while(N--)
{
scanf("%d",&x);
T = Insert(T,x);
}
printf("%d",T->Data);
return 0;
}

--------------------------------------------------------------------------------

雖然簡單可是我還是不會,不過在做題中提升了自我,加油,乾飯人!