-
Notifications
You must be signed in to change notification settings - Fork 0
/
traversal_bst.c
108 lines (97 loc) · 2.45 KB
/
traversal_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
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *root = NULL;
struct node* create(int data){
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode -> data = data;
newnode -> left = NULL;
newnode -> right = NULL;
return newnode;
}
struct node* insert(struct node *root ,int data){
if (root == NULL){
return create(data);
}
else if(data < root->data ){
root->left = insert(root->left,data);
}
else{
root->right = insert(root->right,data);
}
return root;
}
void inorder(struct node*root){
if (root != NULL){
inorder(root -> left);
printf(" %d ", root -> data);
inorder(root->right);
}
}
void preorder(struct node*root){
if (root != NULL){
printf(" %d ", root -> data);
preorder(root -> left);
preorder(root->right);
}
}
void postorder(struct node*root){
if (root != NULL){
postorder(root -> left);
postorder(root->right);
printf(" %d ", root -> data);
}
}
int main(){
int ch=0;
int item;
int pos;
printf("1.Insert 2.InOrder 3.Preorder 4.PostOrder 5.Exit\n");
while (1){
printf("enter choice:");
scanf("%d",&ch);
switch(ch){
case 1: printf("enter:");
scanf("%d",&item);
root = insert(root,item);
break;
case 2: printf("Inorder:");
inorder(root);
printf("\n");
break;
case 3: printf("Preorder:");
preorder(root);
printf("\n");
break;
case 4: printf("Postorder:");
postorder(root);
printf("\n");
break;
case 5: exit(0);
}
}
return 0;
}
output:
1.Insert 2.InOrder 3.Preorder 4.PostOrder 5.Exit
enter choice:1
enter:3
enter choice:1
enter:2
enter choice:1
enter:4
enter choice:1
enter:1
enter choice:1
enter:5
enter choice:2
Inorder: 1 2 3 4 5
enter choice:3
Preorder: 3 2 1 4 5
enter choice:4
Postorder: 1 2 5 4 3
enter choice:5