-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.txt
More file actions
121 lines (109 loc) · 2.68 KB
/
BST.txt
File metadata and controls
121 lines (109 loc) · 2.68 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
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *right;
struct node *left;
};
struct node *CreateBST(struct node*,int);
void Inorder(struct node*);
void Preorder(struct node*);
void Postorder(struct node*);
void main()
{
struct node *root = NULL;
int ch, item,n,i;
while(1)
{
printf("\n\nBinary Search Tree Operations\n");
printf("\n1. Creation of BST");
printf("\n2. Traverse in Inorder");
printf("\n3. Traverse in Preorder");
printf("\n4. Traverse in Postorder");
printf("\n5. Exit\n");
printf("\nEnter Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1 :
printf("Enter the number of nodes : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the data for node %d : ",i);
scanf("%d",&item);
root= CreateBST(root,item);
}
break;
case 2 :
printf("BST Traversal in Inorder\n");
Inorder(root);
break;
case 3 :
printf("BST Traversal in Preorder\n");
Preorder(root);
break;
case 4 :
printf("BST Traversal in Postorder\n");
Postorder(root);
break;
case 5:
printf("TERMINATING");
break;
default :
printf("Invalid option");
break;
}
}
}
struct node *CreateBST(struct node *root, int item)
{
if(root == NULL)
{
root=(struct node*)malloc(sizeof(struct node));
root->left=root->right=NULL;
root->data=item;
return(root);
}
else
{
if(item<(root->data))
{
root->left=CreateBST(root->left,item);
}
else if(item>(root->data))
{
root->right=CreateBST(root->right,item);
}
else
printf("Duplicate element");
return(root);
}
}
void Inorder(struct node *root)
{
if(root!=NULL)
{
Inorder(root->left);
printf("%d\t",root->data);
Inorder(root->right);
}
}
void Preorder(struct node *root)
{
if(root!=NULL)
{
printf("%d\t",root->data);
Preorder(root->left);
Preorder(root->right);
}
}
void Postorder(struct node *root)
{
if(root!=NULL)
{
Postorder(root->left);
Postorder(root->right);
printf("%d\t",root->data);
}
}