forked from keshavsingh4522/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.c
98 lines (98 loc) · 1.69 KB
/
BinarySearchTree.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
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root;
struct node *makenode(int x)
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=x;
p->left=NULL;
p->right=NULL;
return p;
}
int BSTinsert(int key)
{
struct node *x,*y,*z;
x=root;
y=makenode(key);
while(x!=NULL)
{
z=x;
if(x->data<key)
x=x->right;
else
x=x->left;
}
if(key<z->data)
z->left=y;
else
z->right=y;
}
int BSTmin(struct node *s)
{
while(s->left!=NULL)
{
s=s->left;
}
return s->data;
}
int BSTmax(struct node *s)
{
while(s->right!=NULL)
{
s=s->right;
}
return s->data;
}
struct node *BSTsearch(int key)
{
struct node *t;
t=root;
while(t!=NULL)
{
if(t->data==key)
return t;
else
{
if(key<t->data)
t=t->left;
else
t=t->right;
}
}
return NULL;
}
int InOrdertraversal(struct node *t)
{
if(t!=NULL)
{
InOrdertraversal(t->left);
printf(" %d",t->data);
InOrdertraversal(t->right);
}
}
void main()
{
int A[]={13,45,23,67,56,93,72,18,35};
root=NULL;
root=makenode(A[0]);
for(int i=1;i<9;i++)
{
BSTinsert(A[i]);
}
printf("Elements in the binary search tree ->");
InOrdertraversal(root);
int p=BSTmax(root);
printf("\nMax Element->%d",p);
p=BSTmin(root);
printf("\nMin Element->%d",p);
struct node *r=BSTsearch(56);
printf("\nSearched element is present at %u",r);
printf("\nSearched element->%d",r->data);
}