【发布时间】:2013-10-02 04:54:40
【问题描述】:
我不太擅长制作树,而且我完全搞砸了递归。但是,我尝试编写一个程序来将数据插入和显示到树中。
问题是插入根节点后崩溃,不知道为什么。树不算大。只需 10 int。
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct node{
int data;
struct node * left;
struct node * right;
};
void insert(struct node * root,int num){
printf("Insert called for num:%d\n",num);
if(root == NULL){
root = (struct node *)malloc(sizeof(struct node));
root->data = num;
}else if(num > root->data){ // Number greater than root ?
insert(root->right,num); // Let the right sub-tree deal with it
}else if(num < root->data){// Number less than root ?
insert(root->left,num);// Let the left sub-tree deal with it.
}else{
// nothing, just return.
}
}
void display(struct node * root){ // Inorder traversal
if(root->left!=NULL){ // We still have children in left sub-tree ?
display(root->left); // Display them.
}
printf("%d",root->data); // Display the root data
if(root->right!=NULL){ // We still have children in right sub-tree ?
display(root->right); // Display them.
}
}
int main(int argc, char *argv[]) {
int a[10] = {2,1,3,5,4,6,7,9,8,10};
int i;
struct node * tree;
for(i = 0; i < 10;i++){
insert(tree,a[i]);
}
printf("Insert done");
return 0;
}
谁能告诉我哪里出错了?
我知道要求人们在 Stack 上查看您的代码是不受欢迎的,但有时 pair programming 有效:p
更新:
设置struct node * tree = NULL; 后,insert() 方法效果很好。 display() 导致程序崩溃。
【问题讨论】:
-
我立即看到了问题。在分配之后,您永远不会将根节点
left和right指针初始化为 NULL。rootby-val Grijesh 的传球已经介绍过了,所以我不会。 -
@LittleChild 实际上是我和 WhoCraig 的两个错误指针以及下面发布的另一个错误。全面检查您的代码维护
-
@WhozCraig 他们不是默认初始化为 NULL 吗?
-
@LittleChild No.
malloc()只是分配内存。内容是不确定的,直到您在分配后对其进行初始化。本地变量也是如此(Crashworks 在下面的答案中指出了这一点)。 -
@LittleChild 是的,这使得所有分配的内存为零。也不要忘记初始化局部变量,就像 Crashworks 向您指出的那样。
标签: c recursion tree binary-search-tree