标签:== src http iostream each end figure avl ace
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
1 #include<iostream> 2 using namespace std; 3 class node{ 4 public: 5 int val; 6 node *left, *right; 7 node(){left=NULL; right=NULL;} 8 }; 9 10 node* rightRoate(node* root){ 11 node* temp=root->left; 12 root->left=temp->right; 13 temp->right=root; 14 return temp; 15 } 16 17 node* leftRoate(node* root){ 18 node* temp=root->right; 19 root->right=temp->left; 20 temp->left=root; 21 return temp; 22 } 23 24 node* leftRightRoate(node* root){ 25 root->left=leftRoate(root->left); 26 return rightRoate(root); 27 } 28 29 30 31 node* rightLeftRoate(node* root){ 32 root->right=rightRoate(root->right); 33 return leftRoate(root); 34 } 35 36 int getHeight(node* root){ 37 if(root==NULL) return 0; 38 int l=getHeight(root->left), r=getHeight(root->right); 39 return l>r? (l+1):(r+1); 40 } 41 42 node* insert(node* root, int val){ 43 if(root==NULL){ 44 node *newnode=new node(); 45 newnode->val=val; 46 return newnode; 47 } 48 if(root->val>val){ 49 root->left=insert(root->left, val); 50 if(getHeight(root->left)-getHeight(root->right)>1){ 51 if(getHeight(root->left->left)>getHeight(root->left->right)) root=rightRoate(root); 52 else root=leftRightRoate(root); 53 } 54 } 55 else { 56 root->right=insert(root->right, val); 57 if(getHeight(root->right)-getHeight(root->left)>1){ 58 if(getHeight(root->right->right)>getHeight(root->right->left)) root=leftRoate(root); 59 else root=rightLeftRoate(root); 60 } 61 } 62 return root; 63 } 64 65 66 67 int main(){ 68 node *root=NULL; 69 int i, n, t; 70 cin>>n; 71 for(i=0; i<n; i++){ 72 cin>>t; 73 root=insert(root, t); 74 } 75 cout<<root->val<<endl; 76 return 0; 77 }
标签:== src http iostream each end figure avl ace
原文地址:https://www.cnblogs.com/mr-stn/p/9157532.html