I am trying to make the search function for a binary search tree to determine if a value is in the tree. I then want to output back to the user whether it is in the tree or not. This all works, however when i call the search function from my remove function it displays This item is in the tree. I can see why this happens, but i don't know how i can fix it.
bool binarySearchTree::search(int input, bool key){
key = false;
if(root_ptr == NULL){
cout<< "The Tree is Empty";
return NULL;
}
current_ptr = root_ptr;
while(current_ptr !=NULL){
if(current_ptr ->data == input){
cout<< "Item is in the Tree!" << endl;
key = true;
return key;
break;
}
else{
parent_ptr = current_ptr;
if(input > current_ptr ->data){
current_ptr = current_ptr ->right;
}
else
current_ptr = current_ptr ->left;
}
}
if(!key){
cout<< "Data Not in tree" << endl;
returnfalse;
}
}
Whenever i ask to remove an item that is in the tree obviously the item will be in it before it gets removed, and this is why it displays "Item is in the Tree!"?
Anyone know another place i could put this to work properly?
Also if you would like to see other parts of my code, like my header file, and main just ask. Thanks.
I'm not sure why you are calling the search function from the remove function. Can you post your remove function code so I can see what is going on with that?
remove function. The reason i call the search from within the remove is because i need to first see if the item is in the tree inorder to remove it. I originally had a search algorithm within my remove function, but my teacher wants a search function to be seperate so the user can always search for anything. So i figured i would try to use the search function with remove, which does work except for my little hiccup. Anyway here is the remove:
You should probably remove the cout statements inside the search function. If you really want to print that information you can do that from outside the function by checking the return value.
Why would you search for it and not return a pointer to the element? You are basically doing the search operation twice, which is inefficient. When you go to remove the element, you search for it, and if it isn't there than you don't touch anything and just return.