标签:
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 ythe 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
思路:要了解平衡二叉树的插入。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 struct Node 6 { 7 int data; 8 int height; 9 Node *left,*right; 10 }*root,*null; 11 void Init() 12 { 13 null=new Node(); 14 null->left=null->right=NULL; 15 null->height=0; 16 root=null; 17 } 18 void GetHeight(Node * root) 19 { 20 root->height=max(root->left->height,root->right->height)+1; 21 } 22 void L(Node *&root) 23 { 24 Node *temp=root->right; 25 root->right=temp->left; 26 temp->left=root; 27 GetHeight(root); 28 GetHeight(temp); 29 root=temp; 30 } 31 void R(Node *&root) 32 { 33 Node *temp=root->left; 34 root->left=temp->right; 35 temp->right=root; 36 GetHeight(root); 37 GetHeight(temp); 38 root=temp; 39 } 40 Node * Create(int data) 41 { 42 Node *tem=new Node; 43 tem->left=tem->right=null; 44 tem->data=data; 45 tem->height=1; 46 return tem; 47 } 48 void Insert(Node * & root,int data) 49 { 50 if(root==null) 51 { 52 root=Create(data); 53 return; 54 } 55 if(data<root->data) 56 { 57 //LL,LR 58 Insert(root->left,data); 59 GetHeight(root); 60 if(root->left->height-root->right->height==2) 61 { 62 if(root->left->left->height-root->left->right->height==1) 63 { 64 //L 65 R(root); 66 } 67 else if(root->left->left->height-root->left->right->height==-1) 68 { 69 L(root->left); 70 R(root); 71 } 72 } 73 } 74 else 75 { 76 Insert(root->right,data); 77 GetHeight(root); 78 if(root->left->height-root->right->height==-2) 79 { 80 if(root->right->left->height-root->right->right->height==1) 81 { 82 R(root->right); 83 L(root); 84 } 85 else if(root->right->left->height-root->right->right->height==-1) 86 { 87 L(root); 88 } 89 } 90 } 91 } 92 int main(int argc, char *argv[]) 93 { 94 int n,v; 95 Init(); 96 scanf("%d",&n); 97 for(int i=0;i<n;i++) 98 { 99 scanf("%d",&v); 100 Insert(root,v); 101 } 102 printf("%d\n",root->data); 103 return 0; 104 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4301743.html