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

时间:2015-06-08 07:32:10

标签: c++ search recursion binary-search-tree

在我的二叉搜索树中考虑以下搜索功能。

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的数据时,我的程序会在分配数据时崩溃。

我错过了什么?

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

1 个答案:

答案 0 :(得分:3)

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

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