04-樹5 Root of AVL Tree (25分)
An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer NN (20≤20) which is the total number of keys to be inserted. Then NN distinct integer keys are given in the next line. All the numbers in a line are separated by a space. Output Specification:
For each test case, print the root of the resulting AVL tree in one line. Sample Input 1:
588 70 61 96 120
Sample Output 1:
70
Sample Input 2:
788 70 61 96 120 90 65
Sample Output 2:
88
主要思路:
1、二叉平衡樹的插入新結點的四種情況判斷(此處遞迴插入)
2、LL,RR,LR,RL旋轉的實現
#include <iostream>#include <vector>using namespace std;#define Max_Node 1000000typedef struct node//樹的結點{ int left; int right; int height;}Node;int Get_Height(vector<Node>& Tree,int root)//遞迴求該結點在二叉樹中的高度{ int HL,HR,MaxH; if (root) { HL=Get_Height(Tree, Tree[root].left); HR=Get_Height(Tree, Tree[root].right); if (HL>HR) { MaxH=HL; }else { MaxH=HR; } return (MaxH+1); }else { return 0; }}int SingleLeftRotation(int A,vector<Node>& Tree)//LL旋轉{ int B=Tree[A].left; Tree[A].left=Tree[B].right; Tree[B].right=A; Tree[A].height=Get_Height(Tree, A); Tree[B].height=Get_Height(Tree, B); return B;}int SingleRightRotation(int A,vector<Node>& Tree)//RR旋轉{ int B=Tree[A].right; Tree[A].right=Tree[B].left; Tree[B].left=A; Tree[A].height=Get_Height(Tree, A); Tree[B].height=Get_Height(Tree, B); return B;}int DoubleLeftRightRotation(int A,vector<Node>& Tree)//LR旋轉{ Tree[A].left=SingleRightRotation(Tree[A].left, Tree); return SingleLeftRotation(A, Tree);}int DoubleRightLeftRotation(int A,vector<Node>& Tree)//RL旋轉{ Tree[A].right=SingleLeftRotation(Tree[A].right, Tree); return SingleRightRotation(A, Tree);}int AVL_Insertion(int X,vector<Node>& Tree,int T)//二叉平衡樹插入一個新結點{ if(!T) { Tree[X].left=0; Tree[X].right=0; Tree[X].height=0; T=X; }else { if (X<T)//小於當前結點,插入到當前結點的左子樹 { Tree[T].left=AVL_Insertion(X, Tree, Tree[T].left); if (Get_Height(Tree, Tree[T].left)-Get_Height(Tree, Tree[T].right)==2)//插入後出現不平衡的情形(只可能為LL或LR的情形) { if (X<Tree[T].left) { T=SingleLeftRotation(T, Tree); }else { T=DoubleLeftRightRotation(T, Tree); } } }else if(X>T)//大於當前結點,插入到當前結點的右子樹 { Tree[T].right=AVL_Insertion(X, Tree, Tree[T].right); if (Get_Height(Tree, Tree[T].left)-Get_Height(Tree, Tree[T].right)==-2) { if (X>Tree[T].right) { T=SingleRightRotation(T, Tree); }else { T=DoubleRightLeftRotation(T, Tree); } } } } Tree[T].height=Get_Height(Tree, T); return T;}int main(){ vector<Node> Tree(Max_Node); int Root=0; int N=0; cin>>N; int X=0; while (N--) { cin>>X; Root=AVL_Insertion(X, Tree, Root); } cout<<Root; return 0;}