2016-10-30 27 views
0

我試圖在二叉搜索樹(BST)上實現插入操作。我有一個叫做insertpush的函數。每當插入一個值時,調用insert()函數。如果root是null(最初)它將被插入。如果root不爲null,那麼從insert()函數push()將被調用來插入值。但對於我來說,root始終保持爲null。我使用了一個字符串「我在這裏」來檢查每當我嘗試插入一個新的數據時,這個字符串就會被打印。這就是我知道root仍然是NULL的原因。這背後的問題是什麼?爲什麼在二叉樹中root始終爲空

#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

該程序有兩個變量名爲root。第一個是全局變量,另一個是函數插入的局部變量。這就是爲什麼全局變量不能在功能insert中更改的原因。

您可以更改像

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

的界面和使用方式的功能:

root = insert(root,value); 

還有一些方法存在改變全局變量,例如使用該接口:

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

thnx爲您的答覆..我想我需要學習更多關於這個話題:) –

相關問題