-
Notifications
You must be signed in to change notification settings - Fork 10
/
binary_search_tree
90 lines (81 loc) · 1.23 KB
/
binary_search_tree
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
#include<stdio.h>
#include<stdlib.h>
struct Node
{
struct Node* left;
int data;
struct Node* right;
};
struct Node*root=NULL;
struct Node* insert(struct Node* root,int key)
{
struct Node*ptr,*new,*save;
new=(struct Node*)malloc(sizeof(struct Node));
new->left=NULL;
new->right=NULL;
new->data=key;
if(root==NULL)
{
root=new;
}
else
{
save=root;
ptr=root;
while(ptr!=NULL)
{
save=ptr;
if(ptr->data >key) ptr=ptr->left;
else ptr=ptr->right;
}
if(key<save->data)
save->left = new;
else
save->right = new;
}
return root;
}
struct Node* search(int key)
{
int f=0;
struct Node*ptr;
if(root==NULL)
{
printf("Empty");
return root;
}
else
{
ptr=root;
while(ptr!=NULL)
{
if(ptr->data==key)
{
f=1;
break;
}
else if(key>ptr->data)
ptr=ptr->right;
else
ptr=ptr->left;
}
}
f==1?printf("Element %d Is Found",key):printf(" Element %d Is Not Found",key);
}
int main()
{
int d;
printf("press -1 to stop");
printf("\nEnter the elements>>");
scanf("%d",&d);
while(d!=-1)
{
root=insert(root,d);
printf("\nEnter the elements>>");
scanf("%d",&d);
}
printf("\nEnter to search>>");
scanf("%d",&d);
search(d);
return 0;
}