-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.c
141 lines (129 loc) · 2.13 KB
/
bst.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
139
140
141
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 30
struct tree
{
int info;
struct tree *left,*right;
};
typedef struct tree *NODE;
#define MALLOC(p,s,t)\
if(!(p=(t)malloc(s))){\
fprintf(stderr,"Insufficient memory \n");\
exit(0);\
}
NODE create(NODE,int);
NODE createTree(NODE,int);
void inorder(NODE);
void preorder(NODE);
void postorder(NODE);
int search(NODE,int);
int n;
void main()
{
NODE p;
p=NULL;
int done=0,choice,flag,key;
while(!done)
{
printf("1.Create \t 2.Inorder \t 3.Postorder \t 4.Preorder \t 5.Search \t 6.Exit \n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Enter no. of data elements \n");
scanf("%d",&n);
p=create(p,n);
break;
case 2:inorder(p);
break;
case 3:postorder(p);
break;
case 4:preorder(p);
break;
case 5:printf("Enter the key \n");
scanf("%d",&key);
flag=search(p,key);
if(flag==1)
printf("Key found \n");
else
printf("Key not found \n");
break;
case 6:done=1;
break;
default:printf("Illegal Entry \n");
break;
}
}
}
NODE create(NODE root,int n)
{
int i,e;
NODE q;
if(root==NULL)
{
for(i=1;i<=n;i++)
{
printf("Enter data element \n");
scanf("%d",&e);
root=createTree(root,e);
}
return root;
}
else
printf("Tree already exists \n");
}
NODE createTree(NODE p,int e)
{
if(p==NULL)
{
MALLOC(p,sizeof(struct tree),NODE);
p->info=e;
p->left = p->right = NULL;
}
else if(e == p->info)
printf("Duplicate Entry \n");
else if(e < p->info)
p->left=createTree(p->left,e);
else if(e > p->info)
p->right=createTree(p->right,e);
return p;
}
int search(NODE p,int key)
{
if(p==NULL)
return 0;
else if(key == p->info)
return 1;
else if(key < p->info)
return search(p->left,key);
else
return search(p->right,key);
}
void postorder(NODE root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\n",root->info);
}
}
void inorder(NODE root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%d\n",root->info);
inorder(root->right);
}
}
void preorder(NODE root)
{
if(root!=NULL)
{
printf("%d\n",root->info);
preorder(root->left);
preorder(root->right);
}
}