-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBSTTravelsal.c
123 lines (108 loc) · 2.28 KB
/
BSTTravelsal.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
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *tree;
void createtree(struct node *tree);
struct node *insert(struct node *tree, int val);
void preorder(struct node *tree);
void inorder(struct node *tree);
void postorder(struct node *tree);
int main()
{
int option,val;
do
{
printf("\n1.INSERT");
printf("\n2.PREORDER");
printf("\n3.INORDER");
printf("\n4.POSTORDER");
printf("\n5.EXIT");
printf("\nInsert option number : ");
scanf("%d",&option);
createtree(tree);
switch(option)
{
case 1:
printf("Enter the value of new node:");
scanf("%d",&val);
tree=insert(tree,val);
break;
case 2:
preorder(tree);
break;
case 3:
inorder(tree);
break;
case 4:
postorder(tree);
}
}while(option!=5);
}
void createtree(struct node *tree)
{
tree=NULL;
}
struct node *insert(struct node *tree, int val)
{
struct node *ptr,*nodeptr,*parentptr;
ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=val;
ptr->left=NULL;
ptr->right=NULL;
if(tree==NULL)
{
tree=ptr;
tree->left=NULL;
tree->right=NULL;
}
else
{
parentptr=NULL;
nodeptr=tree;
while(nodeptr!=NULL)
{
parentptr=nodeptr;
if(val<nodeptr->data)
nodeptr=nodeptr->left;
else
nodeptr=nodeptr->right;
}
if(val<parentptr->data)
parentptr->left=ptr;
else
parentptr->right=ptr;
}
return tree;
}
void preorder(struct node *tree)
{
if(tree!=NULL)
{
printf("%d\t",tree->data);
preorder(tree->left);
preorder(tree->right);
}
}
void inorder(struct node *tree)
{
if(tree!=NULL)
{
inorder(tree->left);
printf("%d\t",tree->data);
inorder(tree->right);
}
}
void postorder(struct node *tree)
{
if(tree!=NULL)
{
postorder(tree->left);
postorder(tree->right);
printf("%d\t",tree->data);
}
}