C++ 二叉搜索树的广度优先搜索
我正在尝试为二叉搜索树创建一个广度优先的搜索函数,但我似乎无法使它工作。任何指点都将不胜感激C++ 二叉搜索树的广度优先搜索,c++,binary-search-tree,breadth-first-search,C++,Binary Search Tree,Breadth First Search,我正在尝试为二叉搜索树创建一个广度优先的搜索函数,但我似乎无法使它工作。任何指点都将不胜感激 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)
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;
}
模板
boolbst::displayBfs(T searchKey,BST*节点)
{
BST*tmp=节点;
排队;
queue.push(节点->mData);
if(node==NULL)
{
返回false;
}
而(!queue.empty())
{
queue.pop();
if(tmp->mData==searchKey)
返回true;
其他的
{
如果(tmp->mLeft!=NULL)
push(tmp->mLeft->mData);
如果(tmp->mRight!=NULL)
push(tmp->mRight->mData);
}
}
返回false;
}
由于BST
节点具有关于其子节点的信息,因此您必须将它们放入队列中,而不是像现在这样将值放入队列中。另一件事是,在弹出元素之前,您没有从队列中获取该元素。最后,由于std::queue
我假设您正在使用,所以您必须为队列指定其他名称
尝试用以下方式重写您的BFS:
template <class T>
bool BST<T>::displayBfs(T searchKey, BST<T> *node)
{
if (node == NULL) return false;
queue<BST<T>*> q;
q.push(node);
while (!q.empty())
{
BST<T>* tmp = q.front();
q.pop();
if (tmp->mData == searchKey)
return true;
else
{
if(tmp->mLeft != NULL)
q.push(tmp->mLeft);
if(tmp->mRight != NULL)
q.push(tmp->mRight);
}
}
return false;
}
模板
boolbst::displayBfs(T searchKey,BST*节点)
{
如果(node==NULL)返回false;
队列q;
q、 推送(节点);
而(!q.empty())
{
BST*tmp=q.front();
q、 pop();
if(tmp->mData==searchKey)
返回true;
其他的
{
如果(tmp->mLeft!=NULL)
q、 推送(tmp->mLeft);
如果(tmp->mRight!=NULL)
q、 推送(tmp->右侧);
}
}
返回false;
}
几件事:
node==NULL
的测试应在访问节点之前进行:
if (node == NULL)
return false;
queue.push(node);
此外,您的队列应为节点类型,并且您应在队列中插入节点:
队列*>队列
最后,如果您没有访问dequed元素,则需要在调用pop之前使用queue类的front
方法访问front元素。有任何症状吗?是编译错误还是运行时错误?对不起,我忘了我无意中删除了那一行。tmp现在已定义。这是一个运行时错误。我会的,我会的。我得等几分钟。