-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw4-1.c
107 lines (82 loc) · 1.86 KB
/
hw4-1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <malloc.h>
#include <math.h>
typedef struct avltreeNode *avltree;
struct avltreeNode{
int data;
avltree left;
avltree right;
int height;
};
int Max(int a, int b){
return a>b?a:b;
}
int GetHeight(avltree T){
if(!T)
return -1;
return T->height;
}
avltree SingleRightRotation(avltree A){
avltree B = A->right;
A->right=B->left;
B->left=A;
A->height = Max(GetHeight(A->left),GetHeight(A->right))+1;
B->height = Max(GetHeight(B->right),A->height)+1;
return B;
}
avltree SingleLeftRotation(avltree A){
avltree B=A->left;
A->left=B->right;
B->right=A;
A->height = Max(GetHeight(A->left),GetHeight(A->right))+1;
B->height = Max(GetHeight(B->left),A->height)+1;
return B;
}
avltree DoubleLeftRightRotation (avltree A){
A->left=SingleRightRotation(A->left);
return SingleLeftRotation(A);
}
avltree DoubleRightLeftRotation(avltree A){
A->right=SingleLeftRotation(A->right);
return SingleRightRotation(A);
}
avltree insert(int data, avltree T){
if(!T){
T=(avltree)malloc(sizeof(struct avltreeNode));
T->data=data;
T->height=0;
T->left=T->right=NULL;
// printf("%d\n",T->data);
}
else if(data < T->data){
T->left=insert(data,T->left);
if(GetHeight(T->left)-GetHeight(T->right)==2)
if(data < T->left->data)
T=SingleLeftRotation(T);
else
T=DoubleLeftRightRotation(T);
// printf("%d\n",T->data);
}
else if(data > T->data){
T->right=insert(data,T->right);
if(GetHeight(T->left)-GetHeight(T->right)==-2)
if(data > T->right->data)
T=SingleRightRotation(T);
else
T=DoubleRightLeftRotation(T);
// printf("%d\n",T->data);
}
T->height=Max(GetHeight(T->left),GetHeight(T->right))+1;
// printf("height:%d\n",T->height);
return T;
}
int main(){
int num,i,x;
avltree root=NULL;
scanf("%d",&num);
for(i=0;i<num;i++){
scanf("%d",&x);
root=insert(x,root);
}
printf("%d",root->data);
}