I have a problem with searching in a tree structure data in C++. My code is below. Every node in the tree has 3 children. My 'search' function is recursive and I want to determine that is there any node in the tree that has my 'item'. But 'search' does not work. I think my recursion has some problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class tree{
char* key;
tree* left;
tree* mid;
tree* right;
public:
bool search(tree *temp, char *item) //temp is root of tree//
{ //that is initialized //
if (temp == NULL) //in main() //
returnfalse;
if (item == temp->key)
returntrue;
if(search( temp->left,item )) returntrue;
elseif(search( temp->mid,item )) returntrue;
elseif(search( temp->right,item )) returntrue;
elsereturnfalse;
}
};
I can't see anything wrong with the recursion myself.
When you say if (item == temp->key) are you trying to compare strings?
Because that is comparing the pointers, NOT the strings. It is testing if item and temp->key point to the very same string. It does not test if those strings contain the same characters.
Maybe look at #include <cstring> and the function std::strcmp();
Note that strcmp returns 0 when the 2 parameters match. You can likely see what's going wrong by adding some logging functions to your code. In this case, try:
1 2 3 4 5 6 7 8 9
bool search(tree *temp, char *item) //temp is root of tree//
{ //that is initialized //
if (temp == NULL) //in main() //
returnfalse;
std::cout << "item = " << item << std::endl;
std::cout << "temp->key = " << temp->key << std::endl;
if (strcmp(item, temp->key) == 0)
returntrue;
...
Thanks Rollie. I didn't know that strcmp returns 0 when parameters match. And thanks moorecm. I changed my function to 'Search' with capital letter. Below is my modified 'Search' and also main(). But sadly, problem exists. :(