Here I have made a program for deletion in binary search tree(BST), but getting segmentation fault (core dumped) while executing, I think it's in delete function but where don't know if I remove function call for delete function then it works fine, like finding maximum element, inorder traversal, but delete won't work.
#include<stdio.h>
#include<stdlib.h>
struct BST{
int data;
struct BST *left;
struct BST *right;
};
struct BST *newNode(int data){
struct BST *temp = (struct BST *)malloc(sizeof(struct BST));
temp->data=data;
temp->left=0;
temp->right=0;
return temp;
}
void inOrder(struct BST *root){
if(root==0)
return;
inOrder(root->left);
printf("%d",root->data);
inOrder(root->right);
}
struct BST *findMax(struct BST *root){
if(root==0)
return 0;
if(root->right!=0)
return findMax(root->right);
return root;
}
struct BST *dele(struct BST *root,int data){
if(root==0)
return 0;
if(data<root->data)
root->left=dele(root->left,data);
if(data>root->data)
root->right=dele(root->right,data);
else{
if(root->left && root->right)
{
struct BST *temp=findMax(root->left);
root->data=temp->data;
root->left=dele(root->left,root->data);
}
else{
struct BST *temp=root;
if(root->left==0)
root=root->right;
if(root->right==0)
root=root->left;
free(temp);
return root;
}
}
return root;
}
void main(){
struct BST *root = (struct BST*)malloc(sizeof(struct BST));
root=newNode(1);
root->left=newNode(2);
root->right=newNode(3);
root->left->left= newNode(4);
root->left->right=newNode(5);
root->right->left=newNode(6);
root->right->right=newNode(7);
inOrder(root);
root=dele(root,1);
printf("\n\n");
inOrder(root);
}