在我的二进制搜索树中考虑以下搜索功能。
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)
每当我访问/搜索非根数据时,我去分配该数据时程序就会崩溃。
我想念什么?
注意:请理解,也许我可以在遍历中使用函数指针来返回值,但是出于目的,我使用树进行搜索将返回对该对象的引用。
您没有返回对要查找的节点的引用,而是返回了对的引用found
,该引用具有自动存储功能,并且在函数退出时将被销毁。
要解决此问题,您可以创建found
一个指针,将节点的地址存储在其中,然后return *found;
在函数末尾。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句