Return 来自二叉搜索树 C++ 的引用

Return reference from binary search tree C++

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

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)

每当我访问/搜索非根数据时,我的程序在分配该数据时崩溃。

我错过了什么?

注意:请理解,也许我可以在我的遍历中使用一个函数指针来执行 return 值,但为了我使用我的树进行搜索的目的,将 return 引用对象。

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

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