-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinarySearchTreeCreateAndTraversal.c
111 lines (100 loc) · 2.65 KB
/
BinarySearchTreeCreateAndTraversal.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
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node{
struct node *left;
int data;
struct node *right;
};
struct node *root = NULL;
struct node *tree = NULL;
struct node *createNode(int data){
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void createLeaf(struct node *root){
int data;
if(root == NULL){
printf("\nEnter the value of the root element:\t");
scanf("%d",&data);
root = createNode(data);
tree = root;
return;
}
printf("\nEnter the data:\t");
scanf("%d",&data);
while(1){
if(data >= root->data && root->right != NULL){
root = root->right;
}
else if(data < root->data && root->left != NULL){
root = root->left;
}
else{
break;
}
}
if(data >= root->data){
root->right = createNode(data);
}
else{
root->left = createNode(data);
}
}
void inOrderTraversal(struct node *root){
if(root!= NULL){
inOrderTraversal(root->left);
printf("%d ",root->data);
inOrderTraversal(root->right);
}
}
void preOrderTraversal(struct node *root){
if(root != NULL){
printf("%d ",root->data);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
}
void postOrderTraversal(struct node *root){
if(root != NULL){
postOrderTraversal(root->left);
postOrderTraversal(root->right);
printf("%d ",root->data);
}
}
void main(){
while(1){
printf("\n1. Insert into the Tree");
printf("\n2. Serach in the tree");
printf("\n3. Print the three traversals");
printf("\n4. EXIT!");
int ch;
printf("\nEnter your choice:\t");
scanf("%d",&ch);
switch(ch){
case 1:
printf("\nInserting...");
createLeaf(tree);
printf("\ninserted Successfully");
case 2:
printf("\nTo be implemented yet!");
break;
case 3:
printf("\nPreOrderTraversal:\t");
preOrderTraversal(tree);
printf("\ninOrderTraversal:\t");
inOrderTraversal(tree);
printf("\nPostOrderTraversal:\t");
postOrderTraversal(tree);
break;
case 4:
exit(0);
break;
default:
printf("INVALID CHOICE!");
}
}
}