2016-10-30 8 views
0

バイナリ検索ツリー(BST)に挿入操作を実装しようとしています。insertpushという名前の関数があります。値が挿入されるときは、insert()関数が呼び出されます。 (最初に)Nullです。もしrootがnullでなければ、insert()から別の関数push()が呼び出されて値を挿入します。しかし、私のrootは常にnullのままです。新しいデータを挿入しようとするたびに、この文字列が表示されます。ルートがNULLのままであることがわかります。これの背後にある問題は何ですか?バイナリツリーでルートが常にnullの理由

#include<stdio.h> 
struct node { 

    int data; 
    struct node* left; 
    struct node *right; 
}; 
void insert(struct node *root,int value); 
void push(struct node *temp,struct node *newNode); 
struct node *root; 
int main(){ 
    root = NULL; 
    int option,value; 
    for(;;){ 
     printf("Please select an option from below : \n"); 
     printf("1 for insert\n"); 
     printf("2 for search\n"); 
     printf("please enter your option : "); 
     scanf("%d",&option); 
     printf("\n"); 
     switch(option){ 
      case 1: 
       printf("you choose to insert\n"); 
       printf("input your value :"); 
       scanf("%d",&value); 
       insert(root,value); 
       printf("\n"); 
       break; 
      default: 
       break; 

     } 
    } 
} 

void insert(struct node *root,int value){ 
    struct node *newNode = (struct node*)malloc(sizeof(struct node)); 
    struct node *temp = (struct node*)malloc(sizeof(struct node)); 

    newNode->data = value; 
    newNode->left = NULL; 
    newNode->right = NULL; 
    temp = root; 
    if(root==NULL){ 
     printf("i am here"); 
     root = newNode; // enter first node 
    }else{ 

     push(temp,newNode); 
    } 
} 
void push(struct node *temp,struct node *newNode){ 
    printf("others"); 
    if(temp==NULL){ 
     temp = newNode; 
    }else{ 
     if(temp->data > newNode->data){ 
       push(temp->left,newNode); 
     }else{ 
      push(temp->right,newNode); 
     } 
    } 

} 
+3

'root = newNode;'と 'temp = newNode;'は呼び出し元関数の値を変更しないでください。 –

答えて

2

プログラムには、名前がの2つの変数があります。 1つはグローバル変数で、もう1つは関数insertのローカル変数です。そのため、グローバル変数は関数insertでは変更できません。

あなたは

struct node* insert(struct node *root,int value); 

のようなインターフェイスを変更し、道の機能を使用することができます:例えば、

root = insert(root,value); 

いくつかの他の方法がグローバル変数を変更するために存在します

void insert(struct node **root,int value); 
+0

あなたの返信のためのthnx。私はこのトピックについてもっと勉強する必要があると思います:) –

関連する問題