current
is a local variable in the contains()
function. When the function is called recursively, each new call will get it's own set of local variables an won't see what an outer call did to the local variables in the outer function.
Especially, before the recursive call, the function sets the current
node to a node that should be searched next. But the called function will never see that current
variable, it will get its own current
variable, initialize it to root
, and start searching from there.
Each recursive call will start searching from the beginning and then call itself again, until you run out of stack memory and get a stack overflow.
Instead of setting the current
variable you should pass the current node as an additional parameter to the recursive call of the contains()
function.
If you don't want to change the parameters of contains()
the good way to handle this would probably be to move the real work to a helper function that takes deals with the additional parameter:
bool BST::contains(int value) {
return contains_rec(value, root);
}
bool BST::contains_rec(int value, Node *current) {
...
}
If you make the helper function private
you can also make sure nobody gets confused by it's presence or calls it by accident.
Another possibility would be to avoid recursion altogether and use a loop instead.