为什么根在二叉树中总是为空

Why root is always null in Binary Tree

我正在尝试对二叉搜索树 (BST) 执行插入操作。我有一个名为 insertpush 的函数。每当给插入一个值时,insert()函数是 called.If root is Null(initially) 它将是 inserted.If root is not null 然后从 insert() 调用另一个函数 push() 来为我插入 value.But root 始终保持 null.I 使用字符串 "i am here" 进行检查,每次我尝试插入新数据时都会打印此字符串。这就是我如何知道 root 仍然存在 NULL.What 是这背后的问题吗?

#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);
         }
    }

}

程序有两个名为root的变量。第一个是全局变量,另一个是函数插入的局部变量。这就是为什么不能在函数 insert.

中更改全局变量的原因

您可以像这样更改界面

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

并以这种方式使用函数:

root = insert(root,value);

还有其他几种方法可以更改全局变量,例如使用该界面:

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