搜索节点递归错误二进制搜索树-C ++

时间:2020-06-02 05:56:05

标签: c++ search binary-tree

为使此问题尽可能地小,我有一个像这样的递归二叉树函数:

template <class T>

bool Bst<T>::searchTree(const nodeType<T>* p, const T& searchItem) const
{
    if(p == nullptr)
    {
        cout << "Cannot search an empty tree." << endl;
        return false;     //If root is nullptr, that means there is no root node hence no binary tree to begin with
    }
    else
    {
        if(p->info == searchItem)
        {
            return true;
        }
        else if(p->info > searchItem)
        {
            return searchTree(p->rLink, searchItem);
        }
        else
        {
            return searchTree(p->lLink, searchItem);
        }
                                                    //Sets the root node to the pointer current
    }
}

此功能由另一个功能使用:

template <class T>
bool Bst<T>::searchTreeRecursive(const T& searchItem) const
{
    return searchTree(root, searchItem);
}

我在这样的主要方法之一中使用它:

if(dateTree.searchTreeRecursive(newDate))
    {
        cout << "Date has been found." << endl;
    }
    else
    {
        cout << "Date not found." << endl;
    }

其中newDate是名为Date的类的对象,而dateTree是其中包含日期的二进制搜索树。插入后BST很好,因为遍历输出所有值时都存在。

我的问题是,即使我知道输入的日期存在于BST中,我的searchTree函数也满足p==nullptr(p为root)并返回false的条件。谁能找出我的代码中的问题并帮助我?

编辑:对于我的BST中的第一个日期值,如果我进行搜索,它将正确返回。对于BST中第一个值之后的每个值,其值显然都是nullptr。 谢谢

0 个答案:

没有答案
相关问题