forked from krishna14kant/Data-Structures-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch_inBST.cpp
More file actions
119 lines (113 loc) · 1.84 KB
/
binarysearch_inBST.cpp
File metadata and controls
119 lines (113 loc) · 1.84 KB
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
#include<iostream>
using namespace std;
#include<queue>
template <typename t>
class binarytree{
public:
t data;
binarytree* left;
binarytree* right;
binarytree(t data)
{
this->data=data;
left=NULL;
right=NULL;
}
~binarytree()
{
delete left;
delete right;
}
};
binarytree<int>* input2()
{
queue<binarytree<int>*> q;
int rdata;
cout<<"Enter data"<<endl;
cin>>rdata;
binarytree<int>* root=new binarytree<int>(rdata);
q.push(root);
while(q.size()!=0)
{
binarytree<int>* front=q.front();
q.pop();
cout<<"Enter left child of "<<front->data<<endl;
int leftchild;
cin>>leftchild;
if(leftchild!=-1)
{
binarytree<int>* n=new binarytree<int>(leftchild);
front->left=n;
q.push(n);
}
cout<<"Enter right child of "<<front->data<<endl;
int rightchild;
cin>>rightchild;
if(rightchild!=-1)
{
binarytree<int>* n=new binarytree<int>(rightchild);
front->right=n;
q.push(n);
}
}
return root;
}
void print(binarytree<int>* root)
{
queue<binarytree<int>*> q;
q.push(root);
while(q.size()!=0)
{
binarytree<int>* front=q.front();
q.pop();
cout<<front->data<<":";
if(front->left!=NULL)
{
cout<<"L"<<front->left->data;
q.push(front->left);
}
if(front->right)
{
cout<<"R"<<front->right->data;
q.push(front->right);
}
cout<<endl;
}
}
bool bsearch(binarytree<int>* root,int data1)
{
if(root==NULL)
{
return false;
}
if(root->data==data1)
{
return true;
}
else if(data1<root->data)
{
bsearch(root->left,data1);
}
else
{
bsearch(root->right,data1);
}
}
int main()
{
// 4 2 6 1 3 5 7 -1 -1 -1 -1 -1 -1 -1 -1
binarytree<int>* root1=input2();
print(root1);
int x;
cout<<endl<<"Enter element to be searched : "<<endl;
cin>>x;
bool y=bsearch(root1,x);
if(y==1)
{
cout<<"Element Present"<<endl;
}
else
{
cout<<"Element Not Present"<<endl;
}
}