I am trying to create a function for adding a node to BST.
The code for insert function is as below.
void insert(struct node **root,int data){
if(!(*root)){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=data; //how to do without temp node
temp->left=temp->right=NULL;
*root=temp;
return;
}
if(data<(*root)->data){
insert(&(*root)->left,data);
}
else if(data>(*root)->data){
insert(&(*root)->right,data);
}
}
how do i insert the value for the first if condition without using a temp node. I am fairly new to pointers. I am able to get the correct answer but want to avoid using the temp node
EDIT:
this is as per the suggestion of @1201ProgramAlarm As per this i am not getting any output on printing it
struct node{
int data;
struct node *left,*right;
};
//
void print_inorder(struct node * tree)
{
if (tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right);
}
}
void insert(struct node **root,int data){
if(!(*root)){
struct node *temp=(struct node*)malloc(sizeof(struct node));
(*root)->data=data;
(*root)->left=(*root)->right=NULL;
return;
}
if(data<(*root)->data){
insert(&(*root)->left,data);
}
else if(data>(*root)->data){
insert(&(*root)->right,data);
}
}
void main(){
struct node *root=(struct node*)malloc(sizeof(struct node));
root=NULL;
insert(&root,9);
insert(&root,4);
insert(&root,15);
insert(&root,6);
insert(&root,12);
insert(&root,17);
insert(&root,2);
print_inorder(root);
}
EDIT 2: removed the temp initialization in the function and initialized the root as null in main.
void insert(struct node **root,int data){
if(!(*root)){
(*root)->data=data;
(*root)->left=(*root)->right=NULL;
return;
}
if(data<(*root)->data){
insert(&(*root)->left,data);
}
else if(data>(*root)->data){
insert(&(*root)->right,data);
}
}
void main(){
struct node *root=NULL;
insert(&root,9);
insert(&root,4);
insert(&root,15);
insert(&root,6);
insert(&root,12);
insert(&root,17);
insert(&root,2);
printf("Inorder Traversal\n");
print_inorder(root);
}
STill not working. Any help is appreciated as am fairly new to pointers.