-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlevel order traversal.c
98 lines (96 loc) · 1.72 KB
/
level order traversal.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
#include<stdio.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
typedef struct node* tree;
struct qnode
{
struct node* nodeptr;
struct qnode* link;
};
typedef struct qnode* queue;
queue front=NULL,rear=NULL;
tree insert(tree root,int x)
{
if(root==NULL)
{
tree temp=malloc(sizeof(struct node));
temp->data=x;
temp->left=NULL;
temp->left=NULL;
return temp;
}
else if(x<=root->data)
{
root->left=insert(root->left,x);
}
else
{
root->right=insert(root->right,x);
}
return root;
}
void inorder(tree root)
{
if(root==NULL)
return;
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
void qpush(tree tretemp)
{
queue temp=malloc(sizeof(struct qnode));
temp->nodeptr=tretemp;
temp->link=NULL;
if(rear==NULL)
{
rear=temp;
front=temp;
return;
}
rear->link=temp;
rear=temp;
}
void levelorder(tree root)
{
qpush(root);
tree current;
while(front!=NULL)
{
current=front->nodeptr;
printf("%d ",current->data);
if(current->left!=NULL)
qpush(current->left);
if(current->right!=NULL)
qpush(current->right);
front=front->link;
free(current);
}
}
void main()
{
tree root=NULL;
int i,x,n;
printf("\nEnter the Number of elements to be inserted :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the Element %d :",i+1);
scanf("%d",&x);
root=insert(root,x);
}
if(root==NULL)
{
printf("\nThe tree is Empty!!\n");
return;
}
printf("\nINORDER TRAVERSAL OF BST : ");
inorder(root);
printf("\nLEVEL ORDER TRAVERSAL OF BST : ");
levelorder(root);
printf("\n");
}