1. 程式人生 > >《資料結構》04-樹5 Root of AVL Tree

《資料結構》04-樹5 Root of AVL Tree

題目

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 N (≤20) which is the total number of keys to be inserted. Then N 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:

5 88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7 88 70 61 96 120 90 65

Sample Output 2:

88

分析

題目大意就是按順序插入平衡二叉樹,返回該 AVL 樹的根結點值 資料結構(六)平衡二叉樹 看完你就懂了

#include<iostream>
#include<malloc.h>
typedef struct AVLNode *AVLTree;
struct AVLNode{
	int data;     // 存值 
	AVLTree left;
// 左子樹 AVLTree right; // 右子樹 int height; // 樹高 }; using namespace std; // 返回最大值 int Max(int a,int b){ return a>b?a:b; } // 返回樹高,空樹返回 -1 int getHeight(AVLTree A){ return A==NULL?-1:A->height; } // LL單旋 // 把 B 的右子樹騰出來掛給 A 的左子樹,再將 A 掛到 B 的右子樹上去 AVLTree LLRotation(AVLTree A){ // 此時根節點是 A AVLTree B = A->left; // B 為 A 的左子樹 A->left = B->right; // B 的右子樹掛在 A 的左子樹上 B->right = A; // A 掛在 B 的右子樹上 A->height = Max(getHeight(A->left),getHeight(A->right)) + 1; B->height = Max(getHeight(B->left),A->height) + 1; return B; // 此時 B 為根結點了 } // RR單旋 AVLTree RRRotation(AVLTree A){ // 此時根節點是 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->left),A->height) + 1; return B; // 此時 B 為根結點了 } // LR雙旋 AVLTree LRRotation(AVLTree A){ // 先 RR 單旋 A->left = RRRotation(A->left); // 再 LL 單旋 return LLRotation(A); } // RL雙旋 AVLTree RLRotation(AVLTree A){ // 先 LL 單旋 A->right = LLRotation(A->right); // 再 RR 單旋 return RRRotation(A); } AVLTree Insert(AVLTree T,int x){ if(!T){ // 如果該結點為空,初始化結點 T = (AVLTree)malloc(sizeof(struct AVLNode)); T->data = x; T->left = NULL; T->right = NULL; T->height = 0; }else{ // 否則不為空, if(x < T->data){ // 左子樹 T->left = Insert(T->left,x); if(getHeight(T->left)-getHeight(T->right)==2){ // 如果左子樹和右子樹高度差為 2 if(x < T->left->data) // LL 單旋 T = LLRotation(T); else if(T->left->data < x) // LR雙旋 T = LRRotation(T); } }else if(T->data < x){ T->right = Insert(T->right,x); if(getHeight(T->right)-getHeight(T->left)==2){ if(x < T->right->data) // RL 雙旋 T = RLRotation(T); else if(T->right->data < x) // RR單旋 T = RRRotation(T); } } } //更新樹高 T->height = Max(getHeight(T->left),getHeight(T->right)) + 1; return T; } int main(){ AVLTree T=NULL; int n; cin>>n; for(int i=0;i<n;i++){ int tmp; cin>>tmp; T = Insert(T,tmp); } cout<<T->data; return 0; }