binary search tree dfs

I'm doing a depth first search on a binary tree. My function always returns false no matter what I do. I step through the code with break points and it does find the number I'm looking for and return true, ending the function, but then it decides to jump to the last "else" statement and run from there, changing it to false. Why does it keep jump backwards after it returns true?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename T>
bool BST<T>::dfs(BST_Node<T> *node, const T &searchKey)
{
   if(node != NULL)
   {
      if(node->mData == searchKey)
         return true;
      else if(searchKey < node->mData)
         dfs(node->mLeft,searchKey);
      else
         dfs(node->mRight, searchKey);
   }
   return false;
}
You need to pass true all the way back to the original caller. As an example, say that the node that you are searching for is one level below and less than the root node. You call dfs() and then call dfs() again passing a pointer to the left node. That call returns true to the calling dfs() and it has to complete executing so it returns false.

The solution is to return the function calls:
return dfs(node->mLeft,searchKey);
and:
return dfs(node->mRight,searchKey);

Hope that makes sense.
It does make sense, thank you!
Topic archived. No new replies allowed.