binary tree program to delete tree node

Binary tree program to delete tree node:-

#include<stdio.h>
#include<stdlib.h>

//binary tree program

struct node{
int data;
struct node *left;
struct node *right;
};

//struct node *root;

struct node *insert(struct node *node,int x){

if(node==NULL){
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
return newnode;
}
else if (node->data>x){
node->left=insert(node->left,x);
}
else if (node->data<x){
node->right=insert(node->right,x);
}

return node;

}

struct node *delete(struct node *node,int x){

if(node->data==x){
struct node *temp;
if(node->left==NULL && node->right==NULL){
//temp=node;
//node=NULL;
free(node);
return NULL;
}
else if(node->left==NULL){
//struct node *temp=node;
temp=node;
node=node->right;
free(temp);
return node;
}

else if(node->right==NULL){
temp=node;
node=node->left;
free(temp);
return node;
}
else{
//struct node *temp2;
temp=node->right;
//temp2=node;
while(temp->left!=NULL)
temp=temp->left;
//node->data=temp->data;
temp->data=node->data;
temp=delete(temp,temp->data);
printf("the temp->data is %d\n",temp->data);
return node;

}

}
else if (node->data>x){
node->left=delete(node->left,x);
}
else if (node->data<x){
node->right=delete(node->right,x);
}

return node;

}

void print(struct node *node){
if(node==NULL)
return;

print(node->left);
printf("%d  ",node->data);
print(node->right);
}

int main(){

FILE *fp;
fp=fopen("file.txt","r"); //10 5 9 8 6 7 4 1 0 2 45 in file.txt

int n,i,x;
struct node *root=NULL;
fscanf(fp,"%d",&n);

for(i=0;i<n;i++){
fscanf(fp,"%d",&x);
root=insert(root,x);

}

print(root);

printf("enter the element that u want 2 delete?????....\n");
scanf("%d",&x);

if(root!=NULL){
delete(root,x);
}
else
printf("No elements in the binary search tree......\n");

print(root);

return 0;
}

Related Posts