我一直在尝试在C中实现一个简单的二叉搜索树,就像练习一样。我可以在树中插入元素,但在某些点(我无法弄清楚在哪里)我遇到了分段错误。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *left;
struct node *right;
int key;
};
void insert(struct node *treeNode, int key);
void outputTree(struct node *root);
int main(){
//Store how many numbers the user will enter
printf("How many numbers will you enter? > ");
int numNumbers;
scanf("%d", &numNumbers);
//Create a root node
struct node root;
root.key = -1; //-1 Means the root node has not yet been set
root.right = NULL;
root.left = NULL;
//Now iterate numNumbers times
int i;
for(i = 1; i <= numNumbers; ++i){
int input;
scanf("%d", &input);
insert(&root, input);
}
outputTree(&root);
return 0;
}
void insert(struct node *treeNode, int key){
//First check if the node is the root node
if((*treeNode).key == -1){
printf("Root node is not set\n");
(*treeNode).key = key; //If the root node hasn't been initialised
}
else {
//Create a child node containing the key
struct node childNode;
childNode.key = key;
childNode.left = NULL;
childNode.right = NULL;
//If less than, go to the left, otherwise go right
if(key < (*treeNode).key){
if((*treeNode).left != NULL){
printf("Left node is not null, traversing\n");
insert((*treeNode).left, key);
}
else {
printf("Left node is null, creating new child\n");
(*treeNode).left = &childNode;
}
}
else {
//Check if right child is null
if((*treeNode).right != NULL){
printf("Right node is not null, traversing...\n");
insert((*treeNode).right, key);
}
else {
printf("Right node is null, creating new child\n");
(*treeNode).right = &childNode;
}
}
}
}
void outputTree(struct node *root){
//Traverse left
if((*root).left != NULL){
outputTree((*root).left);
}
printf("%d\n", (*root).key);
if((*root).right != NULL){
outputTree((*root).right);
}
}
在编写这个问题时,我刚想到了,是否在堆栈上创建了子节点,所以当递归调用返回时,树中的引用指向不再存在的结构? / p>
这里有什么问题?
谢谢
答案 0 :(得分:1)
您可以通过静态分配在堆栈上创建子节点。插入方法完成后,子引用变为无效。 你应该使用malloc动态分配。
struct node *root = new_node(-1, NULL, NULL);
不要忘记使用免费功能释放所有分配。
编辑: 所以要创建root只需使用
git submodule update --init --recursive