-
Notifications
You must be signed in to change notification settings - Fork 0
/
bttrvsl.cpp
102 lines (100 loc) · 1.98 KB
/
bttrvsl.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
#include<stdio.h>
#include<stdlib.h>
struct btnode{
int d;
struct btnode* l;
struct btnode* r;
};
typedef struct btnode btnode;
struct qnd{
btnode* nd;
struct qnd* next;
};
typedef struct qnd qnd;
void enqueue(qnd** frref,qnd** reref,btnode* data)
{
qnd* newnode=(qnd*)malloc(sizeof(qnd));
newnode->nd=data;
newnode->next=NULL;
if((*frref)==NULL&&(*reref)==NULL)
{
(*frref)=(*reref)=newnode;
return;
}
(*reref)->next=newnode;
(*reref)=newnode;
}
void dequeue(qnd** frref,qnd** reref)
{ qnd* temp=(*frref);
if((*frref)==NULL)
{printf("queue is empty");return;
}
else if((*frref)==(*reref))
{
(*frref)=(*reref)=NULL;
free(temp);
return;
}
(*frref)=(*frref)->next;
free(temp);
}
bool isempty(qnd* frref)
{
if(frref==NULL)return true;
else return false;
}
btnode* insert(int data,btnode* rtref)
{
btnode* newnode=(btnode*)malloc(sizeof(btnode));
newnode->d=data;
newnode->l=newnode->r=NULL;
if(rtref==NULL)
rtref=newnode;
else if(rtref->d>=data)
rtref->l=insert(data,rtref->l);
else
rtref->r=insert(data,rtref->r);
return rtref;
}
void BFStrvsl(btnode* root)
{
qnd* front=NULL;
qnd* rear=NULL;
if(root==NULL)
{printf("error:no tree found\n");
return;
}
enqueue(&front,&rear,root);
while(!isempty(front))
{
btnode* current=front->nd;
printf("%d ",current->d);
if(current->l!=NULL)enqueue(&front,&rear,current->l);
if(current->r!=NULL)enqueue(&front,&rear,current->r);
dequeue(&front,&rear);
}
}
void printInO(btnode* mov)
{ if(mov==NULL)
return;
printInO(mov->l);
printf("%d \t",mov->d);
printInO(mov->r);
}
int main()
{ int n;
btnode* root=NULL;
printf("Enter no of nodes to be inserted\n");
scanf("%d",&n);
printf("Enter nodes\n");
for(int i=0;i<n;i++)
{
int d;
scanf("%d",&d);
root=insert(d,root);
}
printf("Inorder traversal of tree is\n");
printInO(root);
printf("\nBFS traversal of tree is\n");
BFStrvsl(root);
}