为什么这个代码片段给我一个分割错误

Why does this code fragment giving me a segmentation fault?

本文关键字:一个 分割 错误 代码 片段 为什么      更新时间:2023-10-16

我正在写一个二叉搜索树,这个叫做search的函数接受一个值x,搜索树中的节点,并返回它是否是叶子。

bool search(Node<T>* &currentNode, 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;在你的搜索功能