插入字符串时增加二进制搜索树的大小
Incrementing the size of a Binary Search Tree when string is inserted
我正试图插入一个二进制搜索树。目前,每当我增加树的大小时,我都会遇到SIGSEGV分段错误。我的问题是什么?我该怎么修?提前谢谢。
在我的头文件中公开:
bool insert(const Comparable & x)
{
insert(x, root);
}
int size(const Comparable & x)
{
size(x, root);
}
私人在我的头文件:
private:
struct BinaryNode
{
Comparable key;
BinaryNode *left;
BinaryNode *right;
vector<int> lineNumberList;
int size;
BinaryNode(const Comparable & thekey, BinaryNode *lt, BinaryNode *rt)
: key{ thekey }, left{ lt }, right{ rt } { }
BinaryNode(Comparable && thekey, BinaryNode *lt, BinaryNode *rt)
: key{ move(thekey)}, left{ lt }, right{ rt } { }
};
int size(BinaryNode *t)
{
if (t == NULL)
return 0;
else
return (t->left->size) + 1 + (t->right->size);
}
bool insert(const Comparable & x, BinaryNode *t){
if (t == NULL)
{
root = new BinaryNode{ x, NULL, NULL };
t->size++; **Segmentation fault**
return true;
}
else if (x < t->key)
{
insert(x, t->left);
if (insert(x, t->left)){
t->size++; **Segmentation fault**
return true;
}
else
return false;
}
else if (x == t->key)
{
return false;
}
else
{
insert(x, t->right);
if (insert(x, t->right)){
t->size++; **Segmentation fault**
return true;
}
else
return false;
}
}
当t为NULL时,您正试图修改t->size
。在不了解您的设计的情况下,一个盲目的猜测是,如果t为NULL,则t将成为新的根,因此您应该使t=new BinaryNode{ x, NULL, NULL };
而不是root=new BinaryNode{ x, NULL, NULL };
您还可以在不初始化的情况下增加结构的大小,这很糟糕,您应该改为t->size=1;
。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 测试树是否为二进制搜索树
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 二进制搜索树没有匹配的函数调用
- 二进制搜索树不变的标头文件
- 二进制搜索树插入带参数参考
- 搜索非二进制树C 的功能
- 将一个不充实的二进制搜索树转换为完整的二进制搜索树
- 二进制搜索树操作程序错误:分割故障(核心倾倒)
- 二进制搜索树插入垃圾数据
- 二进制搜索树构造的麻烦
- 将二进制搜索树导出到.csv文件
- 检查节点是否是二进制搜索树的根
- 在二进制搜索树中删除节点
- 简单的二进制搜索树非递归添加功能
- 二进制搜索树的数组实现
- 如何从二进制搜索树中删除节点
- 我如何扭转二进制搜索树
- 递归获取二进制搜索树的高度