【发布时间】:2014-04-24 23:37:10
【问题描述】:
这是我在 c 中第一堂课的作业。它侧重于 c 中的动态分配,以 bst 的形式。
我必须有一个动态分配的 BST,递归实现。我知道我的遍历工作正常,并且在插入节点时遇到了麻烦。我只有根节点,其他所有节点似乎都设置为 NULL。我认为遍历时无法打印其余节点,因为我正在尝试访问 NULL 结构的数据成员。到目前为止我的代码如下:
void insert_node(TreeNode** root, int toInsert){
if(*root==NULL){
TreeNode *newnode = (TreeNode *)malloc(sizeof(TreeNode));
newnode->data = toInsert;
newnode->left = NULL;
newnode->right = NULL;
}
else if(toInsert > (*root)->data){ //if toInsert greater than current
struct TreeNode **temp = (TreeNode **)malloc(sizeof(struct TreeNode*));
*temp = (*root)->right;
insert_node(temp, toInsert);
}
else{ //if toInsert is less than or equal to current
struct TreeNode **temp = (TreeNode **)malloc(sizeof(struct TreeNode*));
*temp = (*root)->left;
insert_node(temp, toInsert);
}
}
void build_tree(TreeNode** root, const int elements[], const int count){
if(count > 0){
TreeNode *newroot = (TreeNode *)malloc(sizeof(TreeNode));
newroot->data = elements[0];
newroot->left = NULL;
newroot->right = NULL;
*root = newroot;
for(int i = 1; i < count; i++){
insert_node(root, elements[i]);
}
}
我确定这只是众多问题之一,但我在任何使用“(*root)->data”的行上都会遇到分段错误,我不知道为什么。
附带说明,尽管“(*root)->data”行出现分段错误,但我仍然能够打印“(*root)->data”。怎么可能打印值,但仍然出现分段错误?
【问题讨论】:
-
您不要将您的
newnode附加到insert_node中的树上。
标签: c pointers binary-search-tree dynamic-memory-allocation