-
search binary tree
It has been a while since I built a binary tree from scratch so I decided to do it. Everything works fine but this one function. When I enter a number to search it just keeps running and allowing me to keep enter numbers.
Code:
void tree::search(int key,Node* leaf)
{
if (leaf == NULL)
{
std::cout<<"The tree is empty\n";
}
else if (key==leaf->num)
{
std::cout<<"The number "<<leaf->num<<" was found\n";
}
else if(key < leaf->num)
{
search(key, leaf->left);
}
else if(key > leaf->num)
{
search(key, leaf->right);
}
else
{
std::cout<<"The number "<<key<<"was not found\n";
}
}
void tree::search(int key)
{
Node* current;
current=root;
search(key, current);
}
-
The way you describe it the problem sounds like it could easily be elsewhere. Your search method is a little odd. Is there really a difference between if (leaf == NULL) and a failed search, and is the else ever going to be reached? I don't think so. Besides that being strange, there's nothing wrong with what you posted.
-
It sounds like you aren't entering the function. The function itself seems correct (so long as you have the orientation of the > < correct), except for the last else like WhiteFlags said. You can just move the failed search message into the first if though.
Check to see if you are entering the function. Then if not check the conditions on whatever loop you are using for input to see if they are correct.
-
Lines 20 to 24 are unreachable here. There are no options remaining besides key being either equal to, less than, or greater than leaf->num.
The solution is to realise that the case actually belongs in lines 4-7, and the test for an empty tree cannot be done properly from the recursive function, nor need it be done so.