2016-10-30 24 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为您的答复..我想我需要学习更多关于这个话题:) –

相关问题