我不太擅長製作樹,而且我完全搞砸了遞歸。但是,我試圖製作一個程序來插入和顯示數據到樹中。插入一個根節點後,我的樹程序崩潰了
問題是,它插入到根節點後崩潰,我不知道爲什麼。樹不是太大。只需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()
導致程序崩潰。
我立即看到問題。在分配之後,你永遠不會初始化你的根節點'left'和'right'指針爲NULL。 '根'by-val Grijesh的傳遞已經覆蓋,所以我不會。 – WhozCraig
@LittleChild實際上,我和WhoCraig有兩個錯誤指針,還有一個錯誤發佈在下面。檢查你的代碼充分關注 –
@WhozCraig是不是初始化爲NULL bu默認值? –