-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASSG1_B190513CS_HADIF_1.c
128 lines (119 loc) · 2.25 KB
/
ASSG1_B190513CS_HADIF_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>
#include <stdlib.h>
typedef struct bNode{
int key;
struct bNode *left, *right, *p;
} *node;
typedef struct bTree{
node root;
} *tree;
typedef struct queue{
node *A;
int head, tail;
} *Q;
node insert(tree, int);
void print(tree);
void enq(Q, node);
node deq(Q);
int main()
{
tree T = (tree)malloc(sizeof(struct bTree));
char c;
do
{
int a;
scanf("%c", &c);
switch (c)
{
case 'i':
scanf("%d", &a);
T->root = insert(T, a);
break;
case 'p':
print(T);
printf("\n");
break;
}
} while (c!='e');
return 0;
}
node insert(tree T, int k)
{
node x = (node)malloc(sizeof(struct bNode));
x->key = k;
x->left = x->right = x->p = NULL;
Q q = (Q)malloc(sizeof(struct queue));
q->A = (node*)malloc(500009*sizeof(node));
q->head = q->tail = -1;
if(!T->root)
T->root = x;
else
{
node t = T->root;
while(t)
{
if(t->left)
enq(q, t->left);
else
{
t->left = x;
x->p = t;
free(q->A);
return T->root;
}
if(t->right)
enq(q, t->right);
else
{
t->right = x;
x->p = t;
free(q->A);
return T->root;
}
t = deq(q);
}
}
return T->root;
}
void print(tree T)
{
struct bTree t;
t.root = NULL;
printf("( ");
if(T->root)
{
printf("%d ", T->root->key);
t.root = T->root->left;
print(&t);
t.root = T->root->right;
print(&t);
}
printf(") ");
}
void enq(Q Q, node k)
{
if(Q->head==-1)
{
Q->A[++Q->head] = k;
Q->tail = 1;
}
else if(Q->head!=Q->tail && Q->head!=-1)
{
Q->A[Q->tail] = k;
Q->tail = (Q->tail+1)%500009;
}
else
printf("-1\n");
}
node deq(Q Q)
{
if(Q->head!=-1)
{
int t = Q->head;
Q->head = (Q->head+1)%500009;
if(Q->head==Q->tail)
Q->head = Q->tail = -1;
return Q->A[t];
}
return NULL;
}