-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.c
More file actions
135 lines (126 loc) · 2.88 KB
/
bst.c
File metadata and controls
135 lines (126 loc) · 2.88 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
125
126
127
128
129
130
131
132
133
134
135
//Binary Search Tree
//implimented using linked lists
//with traversal in preorder
//by Simply
#include<stdio.h>
#include<stdlib.h>
struct bst //structure for binary search tree
{
int data;
struct bst *left;
struct bst *right;
}*root,*temp,*q,*p;
struct bst *root=NULL;
void create(int item) //creating the tree by assigning root node
{
root=(struct bst *)malloc(sizeof(struct bst));
root->data=item;
root->left=NULL;
root->right=NULL;
}
void insert(int item)
{
p=root;
q=NULL;
while(p!=NULL) //traverse too find location
{
if(p->data<item)
{
q=p;
p=p->right;
}
else if(p->data>item)
{
q=p;
p=p->left;
}
else
{
printf("Entry already exist");
break;
}
}
temp = (struct bst *)malloc(sizeof(struct bst)); //assign memory location temporarily
temp->data=item;
temp->left=NULL;
temp->right=NULL;
if(q==NULL) //placing the node in the tree
{
root=temp;
}
else if(q->data<item)
{
q->right=temp;
}
else
{
q->left=temp;
}
}
void preorder(struct bst *temp) //display using preorder traversal
{
if(temp!=NULL)
{
printf("%d\t",temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
void postorder(struct bst *temp) //display using postorder traversal
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf("%d\t",temp->data);
}
}
void inorder(struct bst *temp) //display using inorder traversal
{
if(temp!=NULL)
{
inorder(temp->left);
printf("%d\t",temp->data);
inorder(temp->right);
}
}
void main() //main function
{
int item,n,ch;
printf("Creating BST, Enter Data for Root: ");
scanf("%d",&item);
create(item);
while(1) //menu for insert and travers options
{
printf("1.Insert\n2.Preorder\n3.Postorder\n4.Inorder\n5.Exit\n:");
scanf("%d",&ch);
if(ch==1)
{
printf("Enter number of leaves: ");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
printf("Enter Data: ");
scanf("%d", &item);
insert(item);
}
}
else if(ch==2)
{
preorder(root);
printf("\n");
}
else if(ch==3)
{
postorder(root);
printf("\n");
}
else if(ch==4)
{
inorder(root);
printf("\n");
}
else
break;
}
}