C 为什么二叉树中的根总是空的

C 为什么二叉树中的根总是空的,c,struct,binary-tree,C,Struct,Binary Tree,我试图在二进制搜索树上实现insert操作。我有一个名为insert和push的函数。每当给insert赋值时,调用了insert函数。如果root为null,则最初将插入该函数。如果root不为null,则将从insert调用另一个函数push来插入该值。但对我来说,root始终保持null。我使用了一个字符串来检查,每次尝试插入新数据时,都会打印该字符串。这就是我如何知道root保持null的原因。这是什么这背后的问题是什么 #include<stdio.h> struct no

我试图在二进制搜索树上实现insert操作。我有一个名为insert和push的函数。每当给insert赋值时,调用了insert函数。如果root为null,则最初将插入该函数。如果root不为null,则将从insert调用另一个函数push来插入该值。但对我来说,root始终保持null。我使用了一个字符串来检查,每次尝试插入新数据时,都会打印该字符串。这就是我如何知道root保持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);
         }
    }

}

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

您可以像这样更改界面

struct node* insert(struct node *root,int value);
并以这种方式使用该功能:

root = insert(root,value);
还有其他几种方法可以更改全局变量,例如使用该接口:

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

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

您可以像这样更改界面

struct node* insert(struct node *root,int value);
并以这种方式使用该功能:

root = insert(root,value);
还有其他几种方法可以更改全局变量,例如使用该接口:

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

根=新节点;temp=newNode;不要在调用函数中更改它们的值。root=newNode;temp=newNode;不要在调用函数中更改它们的值。thnx用于答复。我想我需要进一步研究此主题:thnx用于答复。我想我需要进一步研究此主题: