-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.c
115 lines (107 loc) · 1.96 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
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *llink,*rlink;
}*root=NULL,*new,*ptr;
int val,ans,a,n=0,x=0;
void createBST(struct node*,int val);
void inorder(struct node*);
void postorder(struct node*);
void preorder(struct node*);
void main()
{
ptr=root;
do
{
printf("Choose Option:\n1:CreateBST\n2:Preorder\n3:Postorder\n4:Inorder\n");
scanf("%d",&ans);
switch(ans)
{
case 1: printf("Enter number of nodes: ");
scanf("%d",&x);
while(n!=x)
{
printf("Enter Value: ");
scanf("%d",&val);
createBST(root,val);
n++;
}
break;
case 2: preorder(root);
break;
case 3: postorder(root);
break;
case 4: inorder(root);
break;
default:printf("Enter Valid input !!");
}
printf("Continue to menue ?(1=Yes)");
scanf("%d",&a);
}while(a==1);
}
void createBST(struct node*ptr,int val)
{
if(root==NULL)
{
new=(struct node*)malloc(sizeof(struct node));
new->llink=new->rlink=NULL;
new->data=val;
root=new;
printf("Root=%d\n",root->data);
}
else if(val<ptr->data)
{
if(ptr->llink==NULL)
{
new=(struct node*)malloc(sizeof(struct node));
new->llink=new->rlink=NULL;
new->data=val;
ptr->llink=new;
printf("%d is left child of %d\n",val,ptr->data);
}
else
createBST(ptr->llink,val);
}
else if(val>=ptr->data)
{
if(ptr->rlink==NULL)
{
new=(struct node*)malloc(sizeof(struct node));
new->llink=new->rlink=NULL;
new->data=val;
ptr->rlink=new;
printf("%d is right child of %d\n",val,ptr->data);
}
else
createBST(ptr->rlink,val);
}
}
void inorder(struct node*ptr)
{
if(ptr!=NULL)
{
inorder(ptr->llink);
printf("%d ",ptr->data);
inorder(ptr->rlink);
}
}
void preorder(struct node*ptr)
{
if(ptr!=NULL)
{
printf("%d ",ptr->data);
preorder(ptr->llink);
preorder(ptr->rlink);
}
}
void postorder(struct node*ptr)
{
if(ptr!=NULL)
{
postorder(ptr->llink);
postorder(ptr->rlink);
printf("%d ",ptr->data);
}
}