-
Notifications
You must be signed in to change notification settings - Fork 1
/
Binary_tree_creation_using_queue.c
138 lines (136 loc) · 3.01 KB
/
Binary_tree_creation_using_queue.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
132
133
134
135
136
137
138
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *lchild;
int data;
struct node *rchild;
};
struct queue
{
int size;
int front;
int rear;
struct node **A;
};
void qcreate(struct queue *q)
{
(*(q)).size = 100;
(*(q)).front = (*(q)).rear = 0;
(*(q)).A = (struct node **)malloc((*(q)).size * sizeof(struct node *));
}
void enqueue(struct queue *q, struct node *p)
{
if (((*(q)).rear + 1) % (*(q)).size == (*(q)).front)
{
printf("Queue is full\n");
}
else
{
(*(q)).rear = ((*(q)).rear + 1) % (*(q)).size;
(*(q)).A[(*(q)).rear] = p;
}
}
struct node *dequeue(struct queue *p)
{
struct node *x = NULL;
if ((*(p)).rear == (*(p)).front)
{
return x;
}
else
{
(*(p)).front = ((*(p)).front + 1) % (*(p)).size;
x = (*(p)).A[(*(p)).front];
return x;
}
}
int isempty(struct queue *q)
{
if ((*(q)).front == (*(q)).rear)
{
return 1;
}
else
{
return 0;
}
}
struct node *tcreate(struct queue *q)
{
struct node *first;
first = (struct node *)malloc(sizeof(struct node));
printf("Enter data in the root:\n");
scanf("%d", &(*(first)).data);
(*(first)).lchild = (*(first)).rchild = NULL;
enqueue(q, first);
while (isempty(q) != 1)
{
struct node *p = NULL;
p = dequeue(q);
printf("Enter data in left child of %d (Enter -1 if no child exists):\n", (*(p)).data);
int num;
scanf("%d", &num);
if (num != (-1))
{
struct node *t;
t = (struct node *)malloc(sizeof(struct node));
(*(t)).data = num;
(*(p)).lchild = t;
(*(t)).lchild = (*(t)).rchild = NULL;
enqueue(q, t);
}
printf("Enter right child of %d (Enter -1 if no child exists):\n", (*(p)).data);
int n;
scanf("%d", &n);
if (n != (-1))
{
struct node *s;
s = (struct node *)malloc(sizeof(struct node));
(*(s)).data = n;
(*(p)).rchild = s;
(*(s)).lchild = (*(s)).rchild = NULL;
enqueue(q, s);
}
}
return first;
}
void preorder(struct node *q)
{
if (q != NULL)
{
printf("%d ", (*(q)).data);
preorder((*(q)).lchild);
preorder((*(q)).rchild);
}
}
void inorder(struct node *q)
{
if (q != NULL)
{
inorder((*(q)).lchild);
printf("%d ", (*(q)).data);
inorder((*(q)).rchild);
}
}
void postorder(struct node *q)
{
if (q != NULL)
{
postorder((*(q)).lchild);
postorder((*(q)).rchild);
printf("%d ", (*(q)).data);
}
}
int main()
{
struct queue q;
qcreate(&q);
struct node *first = NULL;
first = tcreate(&q);
preorder(first);
printf("\n");
inorder(first);
printf("\n");
postorder(first);
}