forked from dishanp/Algorithms-For-Software-Developers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Tree Implementation.c
133 lines (127 loc) · 2.33 KB
/
Binary Search Tree Implementation.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <stdio.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
int c;
struct tree *root=NULL;
void insert(struct tree *t,int key)
{
struct tree *r=NULL;
while(t)
{
r=t;
if(key==t->data)
return;
if(key>t->data)
t=t->right;
else
t=t->left;
}
struct tree *p=( struct tree *)malloc(sizeof( struct tree));
p->data=key;
p->left=p->right=NULL;
if(p->data>r->data)
r->right=p;
else
r->left=p;
}
void create(int n)
{
int x;
for(int i=0;i<n;i++)
{
printf("\nEnter Data of Node %d : ",i+1);
scanf("%d",&x);
insert(root,x);
}
printf("\n");
}
void inorder(struct tree *t)
{
if(t)
{
inorder(t->left);
printf("%d ",t->data);
inorder(t->right);
}
}
struct tree *nMaximum(struct tree *t)
{
while(t->right)
t=t->right;
return t;
}
struct tree *delete(struct tree *t,int key)
{
struct tree *temp;
if(!t)
return t;
if(key<t->data)
t->left=delete(t->left,key);
else if(key>t->data)
t->right=delete(t->right,key);
else
{
if(t->left==NULL)
{
temp=t->right;
free(t);
return temp;
}
else if(t->right==NULL)
{
temp=t->left;
free(t);
return temp;
}
temp=nMaximum(t->left);
t->data=temp->data;
t->left=delete(t->left,temp->data);
}
return t;
}
int search(struct tree *t)
{
printf("\n Enter element to be Searched : ");
int x;
scanf("%d",&x);
if(!t)
return 0;
while(t)
{
if(x==t->data)
return 1;
else if(x<t->data)
t=t->left;
else
t=t->right;
}
return 0;
}
int main()
{
int n;
root=( struct tree *)malloc(sizeof( struct tree ));
printf("Enter Root Node Data : ");
scanf("%d",&root->data);
root->left=root->right=NULL;
printf("\nEnter No Of Nodes In BST: ");
scanf("%d",&n);
create(n);
inorder(root);
printf("\n");
if(search(root))
printf("\nElement is present in BST ! \n");
else
printf("\nElement is not present in BST ! \n");
printf("Enter element for deletion: ");
int a;
scanf("%d",&a);
delete(root,a);
inorder(root);
return 0;
}