Topic Information
1066. Root of AVL Tree (25)
Time limit (MS)
Memory Limit 65536 KB
Code length limit 16000 B
An AVL tree is a self-balancing binary search tree. In a AVL tree, the heights of the subtrees of any node differ by at the most one; If at any time they differ by more than one, the rebalancing is the done to restore this property. Figures 1-4 illustrate the rotation rules.
Now given a sequence of insertions, you is supposed to the root of the resulting AVL tree.
Input Specification:
Each input file contains the one test case. For each case, the first line contains a positive integer N (<=20) which are the total number of keys to being inserted. Then N distinct integer keys is given in the next line. All the numbers in a line is separated by a space.
Output Specification:
For each test case, print ythe root of the resulting AVL tree on 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
Thinking of solving problems
It's not a trick to build an AVL tree.
AC Code
#include <Cstdio>#include <Algorithm>Using namespace std;struct node{node*Left*Right int V, W; node (int value, node*L, node*R): V (value), left (L), right (R), W (0) {}};node*Nil= NewNode0,NULL,NULL); node*Head=NilvoidLeftrotate (node*&Head) {node*T=Head -Right Head -Right=T -Left T -Left=Head Head=T Head -Left -W= Max(Head -Left -Right -W, head -Left -Left -W+ 1; Head -W= Max(Head -Right -W, head -Left -W+ 1;}voidRightrotate (node*&Head) {node*T=Head -Left Head -Left=T -Right T -Right=Head Head=T Head -Right -W= Max(Head -Right -Right -W, head -Right -Left -W+ 1; Head -W= Max(Head -Right -W, head -Left -W+ 1;}voidInsert (node*&Head, int v) {if(Head==Nil) {Head= NewNode (V, nil, nil); }Else if(V>Head -V) {Insert (head -Right, V);if(2 ==Head -Right -W-Head -Left -W) {if(V>Head -Right -V) {leftrotate (head); }Else{Rightrotate (head -right); Leftrotate (head); } } }Else{Insert (head -Left, V);if(2 ==Head -Left -W-Head -Right -W) {if(V<=Head -Left -V) {rightrotate (head); }Else{Leftrotate (head -left); Rightrotate (head); }}} Head -W= Max(Head -Left -W, head -Right -W+ 1;} int main () {int n, A; scanf"%d",&n); while(n--) {scanf ("%d",&a); Insert (head, a); } printf ("%d\n", head -V);return 0;}
Personal game Promotion:
"10 Cloud Square" and block to eliminate the war!
1066. Root of the AVL tree (25) "AVL Trees"--pat (Advanced level) practise