-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAVL.cpp
112 lines (97 loc) · 2.14 KB
/
AVL.cpp
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
108
109
110
111
112
#include <bits/stdc++.h>
#define MAX 5000000
using namespace std;
struct node
{
int data;
int height;
struct node *left, *right;
};
int height(struct node *n)
{
if(n == NULL)
return 0;
return n->height;
}
void rightRotate(struct node **n)
{
struct node *temp;
struct node *temp1;
temp = (*n)->left;
temp1 = *n;
temp1->left = temp->right;
temp->right = temp1;
temp1->height = 1 + max(height(temp1->left), height(temp1->right));
temp->height = 1 + max(height(temp->left), height(temp->right));
*n = temp;
}
void leftRotate(struct node **n)
{
struct node *temp;
struct node *temp1;
temp = (*n)->right;
temp1 = *n;
temp1->right = temp->left;
temp->left = temp1;
temp1->height = 1 + max(height(temp1->left), height(temp1->right));
temp->height = 1 + max(height(temp->left), height(temp->right));
*n = temp;
}
void insert(struct node **node, int value)
{
if(*node == NULL)
{
struct node *newNode = new struct node;
newNode->left = NULL;
newNode->right = NULL;
newNode->data = value;
newNode->height = 1;
*node = newNode;
return;
}
if(value >= (*node)->data)
insert(&(*node)->right, value);
else
insert(&(*node)->left, value);
(*node)->height = 1 + max(height((*node)->left), height((*node)->right));
if(abs(height((*node)->left) - height((*node)->right)) > 1) // IMBALANCE
{
if(value < (*node)->data && value < (*node)->left->data) // LEFT > LEFT
{
rightRotate(node);
}
else if(value < (*node)->data && value >= (*node)->left->data) // LEFT > RIGHT
{
leftRotate(&(*node)->left);
rightRotate(node);
}
else if(value >= (*node)->data && value < (*node)->right->data) // RIGHT < LEFT
{
rightRotate(&(*node)->right);
leftRotate(node);
}
else if(value >= (*node)->data && value >= (*node)->right->data) // RIGHT > RIGHT
{
leftRotate(node);
}
}
}
int main()
{
ios::sync_with_stdio(false);
double elapsed_secs;
clock_t begin;
clock_t end;
struct node *root = NULL;
int temp;
begin = clock();
for(int i=1;i<=MAX;i++)
{
cin >> temp;
insert(&root, temp);
}
end = clock();
elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed_secs << endl;
return 0;
}