-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_element_in_BST.cpp
More file actions
98 lines (93 loc) · 1.84 KB
/
search_element_in_BST.cpp
File metadata and controls
98 lines (93 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
//Write a program to search an element in BST
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* root=NULL;
void createNode(int value){
struct node* newNode=new node();
newNode->data=value;
newNode->left=NULL;
newNode->right=NULL;
if(root== NULL){
root=newNode;
return;
}
struct node* current=root;
struct node* parent=NULL;
while(current !=NULL){
parent=current;
if(value < current->data){
current=current->left;
}else{
current=current->right;
}
}
if(value < parent->data ){
parent->left=newNode;
}else{
parent->right=newNode;
}
}
bool searchElement(node* root, int item) {
if (root == NULL) {
return false;
}
if (root->data == item) {
return true;
}
if (item < root->data) {
return searchElement(root->left, item);
} else {
return searchElement(root->right, item);
}
}
void nodeTravers(struct node* root){
if(root==NULL){
return;
}
cout<<root->data<<" ";
nodeTravers(root->left);
nodeTravers(root->right);
}
int main(){
int op;
int x=1, value;
while(x){
cout<<endl<<"-------MENU--------"<<endl<<endl;
cout<<" 1. Insert Node"<<endl;
cout<<" 2. Display"<<endl;
cout<<" 3. Search"<<endl;
cout<<" 4. Exit"<<endl;
cout<<"Enter any option:";
cin>>op;
switch(op){
case 1:
cout<<"Enter data:";
cin>>value;
createNode(value);
break;
case 2:
nodeTravers(root);
break;
case 3:
cout << "Enter searching element: ";
cin >> value;
if (searchElement(root, value)) {
cout << "Search is successful\n";
} else {
cout << "Item not found\n";
}
break;
case 4:
x=0;
break;
default:
cout<<"Enter correct option!!";
}
}
return 0;
}