为什么这个代码片段给我一个分割错误
Why does this code fragment giving me a segmentation fault?
我正在写一个二叉搜索树,这个叫做search的函数接受一个值x,搜索树中的节点,并返回它是否是叶子。
bool search(Node<T>* ¤tNode, const T& x) const
{
//~ cout << "CURRENT NODE DATA: " << currentNode->data << " : ";
/* FUNCTION: Searches for variable that is passed in X and checks if this value is a leaf or not */
//Left Subtree Search
if (x < binTree<T>::root->data)
{
if ((leaf(currentNode)) == true)
{
return true;
}
else
{
search(currentNode->left, x);
}
}
//Right Subtree Search
else if (x >= binTree<T>::root->data)
{
//If node in right subtree is a node check
if ((leaf(currentNode)) == true)
{
return true;
}
else
{
search(currentNode->right, x);
}
}
//Return false if the node is not a leaf
return false;
} //END OF SEARCH FUNCTION
bool leaf(Node<T>* currentNode) const
{
return ((currentNode->left == nullptr && currentNode->right == nullptr) ? true : false);
}
当我递归调用带有新更新节点的搜索函数时,出现seg故障。二叉树初始化为100个值,并从根开始搜索。
此代码
if (x < binTree<T>::root->data)
正在检查root
,注意currentNode,因此测试将永远不会更改。因此,如果您的x
值小于root->data
,您将继续尝试递归currentNode->left
,直到您命中叶子(如果您幸运的话)或您命中带有NULL左指针的节点,在这种情况下,您将递归currentNode
为NULL,这将导致leaf
中的段故障,当它试图检查currentNode->left
你应该检查currentNode
。您还应该返回search
递归调用的返回值
你必须声明bool leaf(Node<T>* currentNode) const
BEFORE search
简单修复,复制并粘贴bool leaf(Node<T>* currentNode) const;
在你的搜索功能
相关文章:
- 删除映射和分割错误中的一个过去结束元素
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- 为什么最后一个拆分函数会导致分割故障?如何解决此问题
- 在一个动态分配的数组的程序中分割故障
- 另一个C++奇怪的对象创建分割错误
- c++的新手,并得到一个奇怪的分割错误
- 有形状和圆形类,以及点类.创建将点类作为一个参数的圆时出现分割错误
- 试图使用递归找到一个数字的所有因子,最终会得到大数字的分割错误
- 使用MATLAB mex将矢量分配给另一个矢量时出现分割错误
- 如何在c++中检查一个很长的数的可分割性
- 如何分割一个二进制字符串来比较每个数字
- 为什么我得到一个分割错误时,尝试双迭代
- 为什么我得到一个分割错误在这个代码
- 用空格分割一个正/负整数字符串
- 制作一个2d的100x100数组,将其分割成4个25x25不同的输出
- 分割一个数字并存储在int数组中
- 分割LPSTR并将值相加为一个long
- 我的程序给我一个分割错误(c++)
- 为什么我得到一个分割错误,而通过这个向量迭代
- 为什么这个代码片段给我一个分割错误