avl
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 struct node{ 5 node *left; 6 node *right; 7 int height; 8 int data; 9 node(int x):data(x),left(NULL),right(NULL),height(0){} 10 }; 11 struct avl 12 { 13 node* root; 14 int Height(node *NODE) { 15 if(NODE==NULL) return -1; 16 return NODE->height; 17 } 18 node* RightRotate(node *a) { 19 node *b = a->left; 20 a->left = b->right; 21 b->right = a; 22 a->height = max(Height(a->left), Height(a->right)); 23 b->height = max(Height(b->left), Height(b->right)); 24 return b; 25 } 26 node* LeftRotate(node *a) { 27 node *b = a->right; 28 a->right = b->left; 29 b->left = a; 30 a->height = max(Height(a->left), Height(a->right)); 31 b->height = max(Height(b->left), Height(b->right)); 32 return b; 33 } 34 node* LeftRightRotate(node *a) { 35 a->left = LeftRotate(a->left); 36 return RightRotate(a); 37 } 38 node* RightLeftRotate(node* a) { 39 a->right = RightRotate(a->right); 40 return LeftRotate(a); 41 } 42 node* Insert(int x, node* t) { 43 if(t == NULL) { 44 t = new node(x); 45 return t; 46 } else if(x < t->data) { 47 t->left = Insert(x,t->left); 48 if(Height(t->left) - Height(t->right) == 2) { 49 if(x < t->left->data) { 50 t = RightRotate(t); 51 } else { 52 t = LeftRightRotate(t); 53 } 54 } 55 } else { 56 t->right = Insert(x,t->right); 57 if(Height(t->right) - Height(t->left) == 2) { 58 if(x > t->right->data) { 59 t = LeftRotate(t); 60 } else { 61 t = RightLeftRotate(t); 62 } 63 } 64 } 65 t->height = max(Height(t->left), Height(t->right)) + 1; 66 return t; 67 } 68 /*node* Delete(int x,node *t) { 69 if(t==NULL) return NULL; 70 if(t->data == x) { 71 if(t->right == NULL) { 72 node* temp = t; 73 t = t->left; 74 free(temp); 75 } else { 76 node* head = t->right; 77 while(head->left) { 78 head=head->left; 79 } 80 t->data = head->data; //just copy data 81 t->right = Delete(t->data, t->right); 82 t->height = max(Height(t->left), Height(t->right)) + 1; 83 } 84 return t; 85 else if(t->data < x) { 86 Delete(x, t->right); 87 if(t->right) Rotate(x, t->right); 88 } else { 89 Delete(x, t->left); 90 if(t->left) Rotate(x, t->left); 91 } 92 if(t) Rotate(x, t); 93 } 94 }*/ 95 }; 96 avl a; 97 int main() 98 { 99 int n,x; 100 scanf("%d",&n); 101 a.root=NULL; 102 for(int i=0;i<n;i++) 103 { 104 scanf("%d",&x); 105 a.root=a.Insert(x,a.root); 106 } 107 return 0; 108 }