二叉搜索树的广度优先搜索

时间:2012-10-24 05:39:42

标签: 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)
    {
        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;
}

2 个答案:

答案 0 :(得分:2)

由于BST<T>节点具有关于其子节点的信息,因此您必须将它们放在队列中,而不是像您一样将它们放在队列中。另一件事是你在弹出它之前没有从queue获取元素。最后,由于{I}假设您正在使用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;
}

答案 1 :(得分:0)

少数事情:

node == NULL的测试应该在您访问节点之前进行:

if (node == NULL)
    return false;    
queue.push(node);

此外,您的队列应该是节点类型,您应该在队列中插入节点:

队列* GT;排队;

最后你不是没有访问dequed元素,你需要在调用pop之前使用队列类的front方法来访问front元素。