从二叉搜索树C++返回引用

Return reference from binary search tree C++

本文关键字:返回 引用 C++ 搜索树      更新时间:2023-10-16

考虑我的二叉搜索树中的以下搜索函数。

template <class elemType>
elemType& BSTree<elemType>::search(const elemType & searchItem) const
{
    std::cout << "in 1st teir search" << std::endl;
    if (root == NULL)
    {
        std::cout << "Tree is empty, and there for no data will be in this tree." << std::endl;
    }
    else
    {
        std::cout << "Entering 2nd teir search" << std::endl;
        return search(root, searchItem);
    } //End else
} //End search(1param)
template <class elemType>
elemType& BSTree<elemType>::search(nodeType<elemType>* node, const elemType& dataToFind) const
{
    elemType found;
    if (node == NULL)
    {
        std::cout << "Not found. Node is null." << std::endl;
    }
    else
    {
        if (node->data == dataToFind)
        {
            std::cout << "Data found" << std::endl;
            found = node->data;
        }
        else if (node->data < dataToFind)
        {
            std::cout << "Data not found, searching to the RIGHT" << std::endl;
            found = search(node->rLink, dataToFind);
        }
        else
        {
            std::cout << "Data not found, searching to the LEFT" << std::endl;
            found = search(node->lLink, dataToFind);
        }
    } //End else
    return found;
} //End search(2param)

每当我访问/搜索不是root的数据时,当我去分配该数据时,我的程序就会崩溃。

我错过了什么?

注意:理解也许我可以在遍历中使用函数指针来返回值,但出于目的,我使用我的树进行搜索将返回对对象的引用。

您不会返回对要查找的节点的引用,而是返回对 found 的引用,该引用具有自动存储功能,并在函数退出时销毁。

要解决此问题,您可以将found设置为指针,将节点的地址存储在其中,然后在函数末尾return *found;