AL-zami AL-zami - 1 month ago 7
C Question

Why root is always null in Binary Tree

I am trying to implement insert operation on Binary search Tree(BST).I have a function called

insert
and
push
.Whenever a value is given to insert ,
insert()
function is called.If root is Null(initially) it will be inserted.If root is not null then from insert() another function
push()
will be called to insert the value.But for me root always remain null.I used a string "i am here" to check and every time i try to insert a new data this string gets printed .That's how i know root remains NULL.What is the problem behind this?

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

}

Answer

The program have two variables with the name root. The first is the global variable the other is local to the function insert. That's why the global variable can't be changed in the the function insert.

You can change the interface like

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

and use the function that way:

root = insert(root,value);

Several other methods exists to change the global variable, e.g. use that interface:

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