-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASSG3_B190513CS_HADIF_3.c
131 lines (119 loc) · 2.55 KB
/
ASSG3_B190513CS_HADIF_3.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <stdio.h>
#include <stdlib.h>
typedef struct rbNode{
int key;
char color;
struct rbNode *left, *right;
} * node;
typedef struct rbt{
node root;
} *tree;
node createNode(int);
tree insert(tree, int);
node rbInsert(node, node);
node subInsert(node, node);
node leftRotate(node);
node rightRotate(node);
void print(node);
node nil;
int main()
{
tree T = (tree)malloc(sizeof(struct rbt));
nil = (node)malloc(sizeof(struct rbNode));
nil->color = 'B';
nil->key = -1;
nil->left = nil->right = NULL;
T->root = nil;
int x;
while(scanf("%d", &x))
{
T = insert(T, x);
print(T->root);
printf("\n");
}
return 0;
}
node createNode(int c)
{
node x = (node)malloc(sizeof(struct rbNode));
x->key = c;
x->left = nil;
x->right = nil;
x->color = 'R';
return x;
}
tree insert(tree T, int k)
{
node x = createNode(k);
T->root = rbInsert(T->root, x);
if(T->root->color=='R')
T->root->color = 'B';
return T;
}
node rbInsert(node t, node x)
{
if(t==nil)
return t = x;
if(t->key<x->key)
{
t->right = rbInsert(t->right, x);
if(t->right->color=='R' && t->right->left->color+t->right->right->color!=132)
{
if(t->left->color=='R')
{
t->left->color = t->right->color = 'B';
t->color = 'R';
return t;
}
if(t->right->left->color=='R')
t->right = rightRotate(t->right);
t = leftRotate(t);
t->left->color = 'R';
t->color = 'B';
}
}
else if(t->key>x->key)
{
t->left = rbInsert(t->left, x);
if(t->left->color=='R' && t->left->left->color+t->left->right->color!=132)
{
if(t->right->color=='R')
{
t->left->color = t->right->color = 'B';
t->color = 'R';
return t;
}
if(t->left->right->color=='R')
t->left = leftRotate(t->left);
t = rightRotate(t);
t->right->color = 'R';
t->color = 'B';
}
}
return t;
}
node leftRotate(node x)
{
node p = x->right;
x->right = p->left;
p->left = x;
return p;
}
node rightRotate(node x)
{
node p = x->left;
x->left = p->right;
p->right = x;
return p;
}
void print(node T)
{
printf("( ");
if(T!=nil)
{
printf("%d %c ", T->key, T->color);
print(T->left);
print(T->right);
}
printf(") ");
}