-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement dfs14a.txt
110 lines (110 loc) · 2.47 KB
/
implement dfs14a.txt
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
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*left;
struct node*right;
};
struct node*getnode(int n);
struct node*insert(struct node*root,int data);
void preorder(struct node*ptr);
void postorder(struct node*ptr);
void inorder(struct node*ptr);
int main()
{
struct node*root=NULL,*ptr;
int ch,k;
while(1)
{
scanf("%d",&ch);
switch(ch)
{
case 1:scanf("%d",&k);
root=insert(root,k);
break;
case 2:if(root==NULL)
{
printf("\nBST EMPTY");
}
else
{
printf("\nPREORDER TRAVERSAL OF BINARY SEARCH TREE\n");
preorder(root);
}
break;
case 3:if(root==NULL)
{
printf("\nBST EMPTY");
}
else
{
printf("\nINORDER TRAVERSAL OF BINARY SEARCH TREE\n");
inorder(root);
}
break;
case 4:if(root==NULL)
{
printf("\nBST EMPTY");
}
else
{
printf("\nPOSTORDER TRAVERSAL OF BINARY SEARCH TREE\n");
postorder(root);
}
break;
case 5:exit(0);
default:printf("\nInvalid Choice");
}
}
return 0;
}
struct node*getnode(int n)
{
struct node*temp=(struct node*)malloc(sizeof(struct node));
temp->data=n;
temp->left=NULL;
temp->right=NULL;
return temp;
}
struct node*insert(struct node*root,int data)
{
if(root==NULL)
{
root=getnode(data);
return root;
}
else if(data<=root->data)
{
root->left=insert(root->left,data);
}
else
{
root->right=insert(root->right,data);
}
return root;
}
void postorder(struct node*ptr)
{
if(ptr==NULL)
return;
postorder(ptr->left);
postorder(ptr->right);
printf("%d ",ptr->data);
}
void preorder(struct node*ptr)
{
if(ptr==NULL)
return;
printf("%d ",ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
void inorder(struct node*ptr)
{
if(ptr==NULL)
return;
inorder(ptr->left);
printf("%d ",ptr->data);
inorder(ptr->right);
}