-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST
96 lines (86 loc) · 1.74 KB
/
BST
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
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
}node;
node * create(int val){
node * temp =(int*)malloc(sizeof(node));
temp->data = val;
temp->left=temp->right=NULL;
return temp;
}
node * insertBST(node*root,int data){
if(root==NULL){
root=create(data);
}
else if(root->data >= data ){
root->left=insertBST(root->left,data);
}
else{
root->right=insertBST(root->right,data);
}
return root;
}
displaypre(node*root){ // preorder
if(root==NULL){
return;
}
printf("%d ",root->data);
displaypre(root->left);
displaypre(root->right);
}
displayin(node*root){ // preorder
if(root==NULL){
return;
}
displayin(root->left);
printf("%d ",root->data);
displayin(root->right);
}
displaypos(node*root){ // preorder
if(root==NULL){
return;
}
displaypos(root->left);
displaypos(root->right);
printf("%d ",root->data);
}
int main(){
node*root=NULL;
int n;
printf("Enter number of elements for BST: ");
scanf("%d",&n);
int num,ch;
printf("\nEnter elements to insert\n");
for(int i=0;i<n;i++){
scanf("%d",&num);
root=insertBST(root,num);
}
printf("\nElements inserted\n");
while(1){
printf("\n1.Display indorder\n2.Display preoder\n3.Display postorder\n4.Exit\n");
printf("Enter Choice:");
scanf("%d",&ch);
switch(ch){
case 1:{
displayin(root);
break;
}
case 2:{
displaypre(root);
break;
}
case 3:{
displaypos(root);
break;
}
case 4:{
exit(0);
}
default : printf("\nInvalid choice!\n");
}
}
return 0;
}