I’m trying to make a breadth first search function for a binary search tree, but I don’t seem to be able to make it work. Any pointers would be greatly appreciated!
template <class T>
bool BST<T>::displayBfs(T searchKey, BST<T> *node)
{
BST<T> *tmp = node;
queue <int> queue;
queue.push(node->mData);
if (node == NULL)
{
return false;
}
while (!queue.empty())
{
queue.pop();
if (tmp->mData == searchKey)
return true;
else
{
if(tmp->mLeft != NULL)
queue.push(tmp->mLeft->mData);
if(tmp->mRight != NULL)
queue.push(tmp->mRight->mData);
}
}
return false;
}
Since the
BST<T>nodes have the information about their children, you have to put them on the queue, not the values as you are doing. Other thing is that you ain’t getting the element from thequeuebefore popping it. And finally you have to give other name to your queue because of thestd::queueI’m assuming you are using.Try to rewrite your BFS this way: