2013-10-02 108 views
0

我不太擅长制作树,而且我完全搞砸了递归。但是,我试图制作一个程序来插入和显示数据到树中。插入一个根节点后,我的树程序崩溃了

问题是,它插入到根节点后崩溃,我不知道为什么。树不是太大。只需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; 
} 

有人能告诉我我哪里出了错?

我知道这是令人难以接受的请人检查你的代码的堆栈,但有时pair programming作品:P

更新:
设置struct node * tree = NULL;后,insert()方法效果很好。 display()导致程序崩溃。

+1

我立即看到问题。在分配之后,你永远不会初始化你的根节点'left'和'right'指针为NULL。 '根'by-val Grijesh的传递已经覆盖,所以我不会。 – WhozCraig

+0

@LittleChild实际上,我和WhoCraig有两个错误指针,还有一个错误发布在下面。检查你的代码充分关注 –

+0

@WhozCraig是不是初始化为NULL bu默认值? –

回答

2

int main(int argc, char *argv[]) { 
    // ... 
    struct node * tree; 
    // what is the value of tree at this line? 
    for(i = 0; i < 10;i++){ 
     insert(tree,a[i]); 
    } 
    // ... 
} 

是什么在该行的 “树” 指向标?

+0

'tree'指向树的根节点。我简单地命名为“树”。 :) –

+0

不,我的意思是,在该行:“树”变量中包含什么?如果你做了printf(“%x \ n”,树),你会看到什么? – Crashworks

+0

无效。起初,根节点应该是空的。 –

相关问题