-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.cpp
161 lines (120 loc) · 2.39 KB
/
BST.cpp
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
struct node
{
int data;
struct node *lchild,*rchild;
}*root=NULL;
struct node * insert(struct node *ptr,int value)
{
if(ptr==NULL)
{
ptr=(struct node *)malloc(sizeof(struct node));
ptr->lchild=ptr->rchild=NULL;
ptr->data=value;
return ptr;
}
else if(value<ptr->data)
ptr->lchild=insert(ptr->lchild,value);
else if(value>ptr->data)
ptr->rchild=insert(ptr->rchild,value);
return ptr;
}
void search(struct node* ptr, int value)
{
if(ptr!=NULL)
{
if(ptr->data==value)
printf("Found! \n");
else if(value<ptr->data)
search(ptr->lchild,value);
else if(value>ptr->data)
search(ptr->rchild,value);
}
else
printf("Not found!!! \n");
}
struct node * del(struct node *root,int value)
{
if(root==NULL)
return root;
else if(value<root->data)
root->lchild=del(root->lchild, value);
else if(value>root->data)
root->rchild=del(root->rchild,value);
else
{
struct node *temp=NULL;
if(root->rchild==NULL)
{
temp=root->lchild;
return temp;
}
else if(root->lchild==NULL)
{
temp=root->rchild;
return temp;
}
else
{
temp=root->rchild;
while(temp->lchild!=NULL)
temp=temp->lchild;
root->data=temp->data;
root->rchild=del(root->rchild,temp->data);
}
}
return root;
}
int height(struct node *root)
{
if(root==NULL)
return 0;
int lh, rh;
lh=height(root->lchild);
rh=height(root->rchild);
if(lh>rh)
return ++lh;
else
return ++rh;
}
void inorder(struct node* root)
{
if(root==NULL)
return;
inorder(root->lchild);
printf("%d \t",root->data);
inorder(root->rchild);
}
int main()
{
int choice,value;
while(1)
{
printf("Enter your choice : \n 1.Insert Node \n 2.Search \n 3.Delete \n 4.Display(inorder) \n 5.Height \n 6.Exit \n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be inserted \n");
scanf("%d",&value);
root=insert(root,value);
printf("Node inserted \n");
break;
case 2: printf("Enter the element to be searched \n");
scanf("%d",&value);
search(root,value);
break;
case 3: printf("Enter the element to be deleted \n");
scanf("%d",&value);
root=del(root,value);
break;
case 4: inorder(root);
break;
case 5: printf("Height : %d",height(root));
break;
case 6: exit(0);
default: printf("Wrong input! Try again!!! \n");
}
}
}