在二进制搜索树中插入元素时出现Seg Fault 11
Seg Fault 11 when inserting element into binary search tree
我正在用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)
{
...
}
如果rNode
是NULL
,则rNode->data
崩溃。你的意思是把这些if
按相反的顺序排列吗?
相关文章:
- Seg Fault Issue C++ (file IO / getline)
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- C++ - 将元素按升序插入数组的 SEG 错误
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 字符串上的合并排序上的 Seg 错误
- C++函数过载会导致 SEG 故障
- 导致 Seg 错误的 SingleLinkedList 的析构函数
- g++ 9.2.1 (Linux) 会导致 seg 错误,但 Windows 上的代码块不会
- 带升压的 SEG 故障::make_shared / 特征3 内存.h.
- 循环时无法进入:"Segmentation fault"
- 函数抛出seg错误,我不知道为什么
- Microsoft Visual Studio 2019交叉编译CMake库 - 有效,但存在SEG错误
- Getter seg fault
- 创建一个包含要绘制的项的类(seg-fault)
- 为什么这个if语句没有seg-fault[C++]
- 在二进制搜索树中插入元素时出现Seg Fault 11
- Seg-Fault at BST remove() Function
- libusb_get_device_list seg fault