-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.c
More file actions
125 lines (120 loc) · 2.01 KB
/
BinaryTree.c
File metadata and controls
125 lines (120 loc) · 2.01 KB
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
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct Node
{
struct Node* lchild;
int data;
struct Node* rchild;
};
struct Queue
{
int size;
int front;
int rear;
Node** Q;
};
void create(struct Queue* q, int size)
{
q->size = size;
q->front = q->rear = 0;
q->Q = (Node**)malloc(q->size * sizeof(Node*));
}
void enqueue(struct Queue* q, struct Node* x)
{
if ((q->rear + 1) % q->size == q->front)
printf("Queue is Full");
else
{
q->rear = (q->rear + 1) % q->size;
q->Q[q->rear] = x;
}
}
struct Node* dequeue(struct Queue* q)
{
struct Node* x = NULL;
if (q->front == q->rear)
printf("Queue is Empty\n");
else
{
q->front = (q->front + 1) % q->size;
x = q->Q[q->front];
}
return x;
}
int isEmpty(struct Queue q)
{
return q.front == q.rear;
}
struct Node* root = NULL;
void Treecreate()
{
struct Node* p, * t;
int x;
struct Queue q;
create(&q, 100);
printf("Enter root value");
scanf("%d", &x);
root = (struct Node*)malloc(sizeof(struct Node));
root->data = x;
root->lchild = root->rchild = NULL;
enqueue(&q, root);
while (!isEmpty(q))
{
p = dequeue(&q);
printf("Enter left child of %d", p->data);
scanf("%d", &x);
if (x != -1)
{
t = (struct Node*)malloc(sizeof(struct Node));
t->data = x;
t->lchild = t->rchild = NULL;
p->lchild = t;
enqueue(&q, t);
}
printf("Enter right child %d", p->data);
scanf("%d", &x);
if (x != -1)
{
t = (struct Node*)malloc(sizeof(struct Node));
t->data = x;
t->lchild = t->rchild = NULL;
p->rchild = t;
enqueue(&q, t);
}
}
}
void Preorder(struct Node* p)
{
if (p)
{
printf("%d ", p->data);
Preorder(p->lchild);
Preorder(p->rchild);
}
}
void Inorder(struct Node* p)
{
if (p)
{
Inorder(p->lchild);
printf("%d ", p->data);
Inorder(p->rchild);
}
}
void Postorder(struct Node* p)
{
if (p)
{
Postorder(p->lchild);
Postorder(p->rchild);
printf("%d ", p->data);
}
}
int main(int argc, char* argv[]) {
Treecreate();
Preorder(root);
printf("\nPost Order ");
Postorder(root);
return 0;
}