2016-04-23 58 views
-1

CでBSTを書く際に問題があります。セグメンテーションフォールトエラーが発生し続けます。私は問題がinsertNode関数に起因すると信じています。 printf()ステートメントを関数に追加し、関数呼び出しの直後にnewNodeが追加されているかどうかを確認しました。 insertNode関数を機能させるだけで、コードの残りの部分を無視してください。Cのバイナリ検索ツリー、セグメンテーションフォールトエラー

#include <stdio.h> 
#include <stdlib.h> 

//structure for node 
struct btNode { 
    int data; 
    struct btNode *left; 
    struct btNode *right; 
}; 

//prototypes 
struct btNode* createNode(int x); 
void insertNode(struct btNode *tree, struct btNode *root); 

int main(){ 
    int x,n=-1,i=0; //local variables 

    struct btNode *head=NULL; 

    while (n <= 0){ 
     printf("Enter the number of nodes in the Tree(>0): "); 
     scanf("%i", &n); 
    } 


    while(i < n){ 
     printf("Enter an integer: "); 
     scanf("%i", &x); 
     struct btNode *newNode=createNode(x); 
     insertNode(head,newNode); 
     printf("%d",head->data); //breaks program here???? 

     i++; 
    } 

    while (x < 0){ 
     printf("Enter a integer from 0-5: "); 
     scanf("%i",&x); 

     if (x == 0){ 
      printf("Program Exit.\n"); 

      exit(0); 

     }else if(x==1){ 


     }else if(x==2){ 


     }else if(x==3){ 

     }else if (x==4){ 

     }else if(x==5){ 

     } 

     x=-1; 
    } 

    return 0; 
} 

//creates and returns a pointer to a new node 
struct btNode* createNode(int x) 
{ 
    struct btNode *newNode; 
    newNode=(struct btNode*)malloc(sizeof(struct btNode)); 

    if (newNode == NULL){ 
     printf("Memory Allocation Failed./n"); 
     exit(20); 
    }else{ 
     newNode->data=x; 
     newNode->left=NULL; 
     newNode->right=NULL; 
     return newNode; 
    } 
} 


void insertNode(struct btNode *tree, struct btNode *newNode){ 
    if (tree==NULL){ 
     tree=newNode; 
     printf("%d",tree->data); //works fine here! 
    }else if(tree->data <= newNode->data){ 
     insertNode(tree->right, newNode); 
    }else if(tree->data > newNode->data){ 
     insertNode(tree->left, newNode); 
    } 
} 
+0

を。あなたのプログラムは、最初のループでEOFか数字以外のもの(例えば 'a')を受け取ると停止しません。 'scanf()'などの結果を常にテストしてください。ある値を期待している場合は '1'を返します。 '0'(入力されたものが数字ではないことを示す)または' EOF'を返すかもしれません。 –

+1

この質問は事実上、多くの他のものと重複しています。リストとツリーの両方は、「どのように情報を呼び出しコードに戻すか」という基本的な問題に遭遇します。 –

答えて

1

ツリー構造に挿入した後にnodeを返す必要があります。だからあなたの正しい機能は次のとおりです。

struct btNode *insertNode(struct btNode *tree, struct btNode *newNode){ 
    if (tree==NULL){ 
     tree=newNode; 
     printf("%d", tree->data); //works fine here! 
     return tree; 
    }else if(tree->data <= newNode->data){ 
     tree->right = insertNode(tree->right, newNode); 
     return tree; 
    }else if(tree->data > newNode->data){ 
     tree->left = insertNode(tree->left, newNode); 
     return tree;  
    } 
} 

はまた、あなたのコール修正:あなたは `のscanf()`からの戻り値をテストする必要があり

head = insertNode(head, newNode); 
+0

@OldProgrammerが暗示しているように、関数が 'struct btNode ** tree'を取るようにしてください。 –

+0

@JonathanLeffler私は私の友人がいます。 –

+0

だから私は参照してください;私が編集に行くまで、それは(私のために、私はHTTPS Everywhereを使うので)表示されませんでした... –