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 N (≤) 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
#include <cstdio> #include <stdlib.h> typedef struct AVLNode * AVLTree; typedef AVLTree Position; 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); void calcHeight(AVLTree T); //core function AVLTree rightRotation (AVLTree ); AVLTree RLRotation(AVLTree ); AVLTree leftRotation(AVLTree ); AVLTree LRRotation(AVLTree ); AVLTree Insert(AVLTree T, int x); int main() { int n, v; scanf("%d", &n); AVLTree avt = NULL; for(int i=0; i<n; i++) { scanf("%d", &v); avt = Insert(avt, v); } printf("%d\n", avt->data); } AVLTree Insert(AVLTree T, int x) { if(!T) { T = (AVLTree) malloc(sizeof(struct AVLNode)); T->data = x; T->left = NULL; T->right = NULL; } 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 = rightRotation(T); } else T = RLRotation(T); } } /* else if right_insertion*/ 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 = leftRotation(T); } else T = LRRotation(T); } } /* else if left_insertion*/ //update height calcHeight(T); return T; } int getHeight(AVLTree T) { if (!T) { return 0; } else return T->height; } void calcHeight(AVLTree T) { T->height = max(getHeight(T->left), getHeight(T->right)) + 1; } AVLTree rightRotation (AVLTree A) { AVLTree B = A->right; A->right = B->left; B->left = A; calcHeight(A); calcHeight(B); return B; } AVLTree leftRotation(AVLTree A) { AVLTree B = A->left; A->left = B->right; B->right = A; calcHeight(A); calcHeight(B); return B; } AVLTree RLRotation(AVLTree T) { T->right = leftRotation(T->right); return rightRotation(T); } AVLTree LRRotation(AVLTree T) { T->left = rightRotation(T->left); return leftRotation(T); }