0

I am trying to delete the leaf nodes in a bst which i have created non-recursively. The problem is when i am trying to delete the leaf node i hit a segmentation fault and i have no clue as to why its happening. I believe the code which i have commented is causing the problem. Is it wrong or are there any other ways of deleting any node from the bst ??

```
#include <stdio.h>
#include <stdlib.h>
struct BSTnode
{
int data;
struct BSTnode *left,*right,*parent;
};
typedef struct BSTnode node;
void insert(node **root,int val)
{
node *ptr,*newptr;
newptr=(node *)malloc(sizeof(node));
newptr->left=NULL;
newptr->right=NULL;
newptr->parent=NULL;
newptr->data=val;
if((*root)==NULL)
{
(*root)=newptr;
return;
}
ptr=(*root);
while(ptr!=NULL && ptr->data!=val)
{
if(ptr->data >val )
{
if(ptr->left!=NULL)
ptr=ptr->left;
else
{
ptr->left=newptr;
newptr->parent=ptr;
break;
}
}
else
{
if(ptr->right!=NULL)
ptr=ptr->right;
else
{
ptr->right=newptr;
newptr->parent=ptr;
break;
}
}
}
}
void deleteLeaf(node **root)
{
node *leafParent=NULL;
if((*root)->left!=NULL)
deleteLeaf(&((*root)->left));
if((*root)->right!=NULL)
deleteLeaf(&((*root)->right));
if((*root)->left==NULL && (*root)->right==NULL)
{
/* leafParent=(*root)->parent;
if(leafParent->left==(*root))
leafParent->left=NULL;
else
leafParent->right=NULL;
*/
free(*root);
}
}
void inorder(node *root)
{
if(root->left!=NULL)
inorder(root->left);
printf(" %d ", root->data);
if(root->right!=NULL)
inorder(root->right);
}
main()
{
node *root=NULL;
int i,n,val;
printf("\n How many elements ?");
scanf("%d",&n);
for(i=0;i<n;++i)
{
scanf("%d",&val);
insert(&root,val);
}
printf("\n Inorder traversal : ");
inorder(root);
deleteLeaf(&root);
printf("\n Inorder traversal : ");
inorder(root);
}
```