-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinarySearchTree_traversal.c
More file actions
124 lines (108 loc) · 2.58 KB
/
Copy pathBinarySearchTree_traversal.c
File metadata and controls
124 lines (108 loc) · 2.58 KB
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
124
//Recursively tree traversal by inorder,preorder,and postorder
#include<stdio.h>
#include<stdlib.h>
struct treeNode{
int value;
struct treeNode *lptr;
struct treeNode *rptr;
};
void insert_val(struct treeNode ** root,int val){
struct treeNode * newNode,*temp;
temp = (*root);
newNode = (struct treeNode *)malloc(sizeof(struct treeNode));
if(newNode==NULL){
printf("error in malloc\n");
}
newNode->value = val;
newNode->lptr = NULL;
newNode->rptr = NULL;
if((*root) == NULL){
(*root) = newNode;
return;
}
while(1){
if(val < temp->value){
if(temp->lptr == NULL){
temp->lptr = newNode;
break;
}
temp = temp->lptr;
}
else{
if(temp->rptr == NULL){
temp->rptr = newNode;
break;
}
temp = temp->rptr;
}
}
}
/*
called as: root = insert(root,value);
function defination:
int insert(root ,v){
if(root == NULL)
create Node;
return node as root
}
if(v < root->value)
root->left = insert(root->left,v)
else
root->right = insert(root->right,v)
}
*/
void preorder(struct treeNode * r){
if(r != NULL){
printf("%d ",r->value);
preorder(r->lptr);
preorder(r->rptr);
}
}
void inorder(struct treeNode * r){
if(r != NULL){
inorder(r->lptr);
printf("%d ",r->value);
inorder(r->rptr);
}
}
void postorder(struct treeNode * r){
if(r != NULL){
postorder(r->lptr);
postorder(r->rptr);
printf("%d ",r->value);
}
}
int main(){
int n,val;
struct treeNode *root;
root = NULL;
printf("Enter 1 for insert\n");
printf("Enter 2 for traverse preorder\n");
printf("Enter 3 for traverse inorder\n");
printf("Enter 4 for traverse postorder\n");
printf("Enter 5 for EXIT\n");
scanf("%d",&n);
while(n!=5){
switch(n){
case 1:
printf("Enter the value you want to be insert:\n");
scanf("%d",&val);
insert_val(&root,val);
break;
case 2:
preorder(root);
break;
case 3:
inorder(root);
break;
case 4:
postorder(root);
break;
default:
printf("Enter proper value\n");
}
printf("Enter which operation you want to do again\n");
scanf("%d",&n);
}
return 0;
}