【问题标题】:Why does this code fragment giving me a segmentation fault?为什么这段代码片段会给我一个分段错误?
【发布时间】:2014-03-31 07:56:28
【问题描述】:

我正在编写一个二叉搜索树,这个名为 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);        
}

当我用新的更新节点递归调用搜索函数时,会发生段错误。二叉树初始化为 100 个值,并从根开始搜索。

【问题讨论】:

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


    【解决方案1】:

    这段代码

    if (x < binTree<T>::root->data)
    

    正在检查root,注意currentNode,所以测试永远不会改变。因此,如果您的x 值小于root-&gt;data,您将继续尝试通过currentNode-&gt;left 进行递归,直到您遇到叶子(如果幸运的话)或者您遇到带有NULL 左指针的节点,在这种情况下,您将递归 currentNode 为 NULL,这将导致 leaf 在尝试检查 currentNode-&gt;left 时出现段错误

    您应该检查currentNode。您还应该返回 search 递归调用的返回值

    【讨论】:

      【解决方案2】:

      你必须声明
      bool leaf(Node&lt;T&gt;* currentNode) const
      之前搜索

      在搜索功能之前轻松修复、复制和粘贴bool leaf(Node&lt;T&gt;* currentNode) const;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-25
        • 1970-01-01
        • 1970-01-01
        • 2010-10-19
        • 1970-01-01
        • 2017-08-18
        相关资源
        最近更新 更多