-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathlevel order traversal.cpp
111 lines (92 loc) · 1.36 KB
/
level order traversal.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
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct tree
{
int a;
struct tree *left;
struct tree *right;
}node;
node *queue[100];
int front = -1;
int rear = 0;
void enqueue(node *root)
{
queue[rear] = root;
rear++;
}
node* dequeue()
{
front++;
node *c = queue[front];
return c;
}
void levelorder(node *root)
{
node *q;
printf("\n");
enqueue(root);
while(rear-1!=front)
{
// printf("\nrear = %d , front = %d",rear , front);
q = dequeue();
printf("%d\t",q->a);
if(q->left)
enqueue(q->left);
if(q->right)
enqueue(q->right);
}
}
int main()
{
int n , i;
node *p , *q , *root;
printf("Enter the number of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if(i == 0)
{
p = (node*)malloc(sizeof(node));
scanf("%d",&p->a);
p->left = NULL;
p->right = NULL;
q = p;
root = p;
}
else
{
p = (node*)malloc(sizeof(node));
scanf("%d",&p->a);
p->left = NULL;
p->right = NULL;
q = root;
while(1)
{
if(p->a > q->a)
{
if(q->right == NULL)
{
q->right = p;
break;
}
else
q = q->right;
}
else
{
if(q->left == NULL)
{
q->left = p;
break;
}
else
q = q->left;
}
}
}
}
printf("Level order Traversal is :- ");
levelorder(root);
return 0;
}