在二进制搜索树中插入元素时出现Seg Fault 11

Seg Fault 11 when inserting element into binary search tree

本文关键字:Seg Fault 元素 二进制 搜索树 插入      更新时间:2023-10-16

我正在用C++编写一个程序,我不明白为什么我总是出现分段错误。以下是我目前使用的代码中给我带来麻烦的部分:

在我的主要功能中:

Tree* myTree;
myTree = CreateBST();
const Element a = 23;
InsertBST(myTree, a);
const Element b = 8;   //If I get rid of this line and the next one, the error goes away.
InsertBST(myTree, b);  //But I need to be able to insert data into my tree beyond just the root!

然后是insertBST函数本身及其辅助函数:

void InsertBST(Tree * rTree, const Element nData){
    rTree->root = InsertNodeBST(rTree->root, nData);
}    
//========================================================================================
TreeNode* InsertNodeBST(TreeNode* rNode, const Element nData)
{
    if(rNode->data == -999)   //A new tree's root->data will always be initialized to -999
   {
       TreeNode* rNew = new TreeNode;
       rNew->data = nData;
       rNew->left = NULL;
       rNew->right = NULL;
       return rNew;
   }
   else if(rNode == NULL)
   {
       TreeNode* rNew = new TreeNode;
       rNew->data = nData;
       rNew->left = NULL;
       rNew->right = NULL;
       return rNew;
   }
   else if(nData == rNode->data)
   {
       return rNode;
   }
   else if(nData < rNode->data)
   {
       rNode->left = InsertNodeBST(rNode->left, nData);
       return rNode;
   }
   else
   {
       rNode->right = InsertNodeBST(rNode->right, nData);
       return rNode;
   }
}

我们需要使用的结构如下:

struct TreeNode {
  Element data;
  TreeNode *left;
  TreeNode *right;
};
struct Tree{
    TreeNode *root;
};

有人看到我明显缺少的可能导致我分割错误的东西吗?我是CS的新手,我正在上7年来的第一堂CS课,所以如果这是一个明显的错误,我深表歉意。谢谢

if (rNode->data == -999)
{
    ...
}
else if (rNode == NULL)
{
    ...
}

如果rNodeNULL,则rNode->data崩溃。你的意思是把这些if按相反的顺序排列吗?