How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false"
void search(Node* root, int checkV){
if(checkV > root->data){
search(root->right, checkV);
}
if(checkV < root->data){
search(root->left, checkV);
}
if(checkV == root->data){
cout << "true"<<endl;
}
else{
cout << "false"<<endl;
}
}
CodePudding user response:
If you need to use function "search", then first you should check if root points the nullptr, then if you found data and only after that you should search. Something like this:
void search(Node* root, int checkV) {
if (root->data == nullptr) {
cout << "false" << endl;
}
else if (checkV == root->data) {
cout << "true" << endl;
}
else if (checkV > root->data) {
search(root->right, checkV);
}
else {
search(root->left, checkV);
}
}
But it would be better, if you return bool from search and print result according to that
bool search(Node *root, int checkV) {
if (root == nullptr)
return false;
if (root->data == checkV)
return true;
return root->data < checkV ? check(root->left, checkV) : check(root->right, checkV);
}
CodePudding user response:
I suggest you to modify your function so that it returns bool
variables. To implement the function properly, think about the cases in which you don't find the node you are looking for. In such cases, eventually you will get a nullptr
, that is Node* root
won't point to an existing object. You can construct the if-else
blocks as below.
bool search(Node* root, int checkV){
if(root == nullptr) return false;
else if(checkV > root->data) search(root->right, checkV);
else if(checkV < root->data) search(root->left, checkV);
else if(checkV == root->data) return true; // you can use else as well
}
// Print out true if node exists, otherwise false.
cout << search(root, 5) << endl;