-
Notifications
You must be signed in to change notification settings - Fork 2
/
Fulltree.c
117 lines (108 loc) · 2.66 KB
/
Fulltree.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
#include <stdio.h>
struct tnode
{
int data;
struct tnode *right;
struct tnode *left;
};
struct tnode *CreateBST(struct tnode *, int);
void Inorder(struct tnode *);
void Preorder(struct tnode *);
void Postorder(struct tnode *);
int main()
{
struct tnode *root = NULL;
int choice, item, n, i;
do
{
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",&choice);
switch(choice)
{
case 1:
root = NULL;
printf("\n\nBST for How Many Nodes ? ");
scanf("%d",&n);
for(i = 1; i <= n; i++)
{
printf("\nEnter data for node %d : ", i);
scanf("%d",&item);
root = CreateBST(root,item);
}
printf("\nBST with %d nodes is ready to Use!!\n", n);
break;
case 2:
printf("\nBST Traversal in INORDER \n");
Inorder(root);
break;
case 3:
printf("\nBST Traversal in PREORDER \n");
Preorder(root);
break;
case 4:
printf("\nBST Traversal in POSTORDER \n");
Postorder(root);
break;
case 5:
printf("\n\n Terminating \n\n");
break;
default:
printf("\n\nInvalid Option !!! Try Again !! \n\n");
break;
}
} while(choice != 5);
return 0;
}
struct tnode *CreateBST(struct tnode *root, int item)
{
if(root == NULL)
{
root = (struct tnode *)malloc(sizeof(struct tnode));
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 !! Not Allowed !!!");
return(root);
}
}
void Inorder(struct tnode *root)
{
if( root != NULL)
{
Inorder(root->left);
printf(" %d ",root->data);
Inorder(root->right);
}
}
void Preorder(struct tnode *root)
{
if( root != NULL)
{
printf(" %d ",root->data);
Preorder(root->left);
Preorder(root->right);
}
}
void Postorder(struct tnode *root)
{
if( root != NULL)
{
Postorder(root->left);
Postorder(root->right);
printf(" %d ",root->data);
}
}