title: Deleting the leaf nodes of a binary search tree - segmentation fault
body: <p>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 the idea of deleting that node wrong or are there any other ways of deleting any node from the BST ? </p>
  
  <pre><code>     #include &lt;stdio.h&gt;
       #include &lt;stdlib.h&gt;
  
        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-&gt;left=NULL;
       newptr-&gt;right=NULL;
       newptr-&gt;parent=NULL;
       newptr-&gt;data=val;
  
       if((*root)==NULL)
      {
       (*root)=newptr;
       return;
      } 
  
       ptr=(*root);  
  
       while(ptr!=NULL &amp;&amp; ptr-&gt;data!=val)
      {
        if(ptr-&gt;data &gt;val )
       {
         if(ptr-&gt;left!=NULL)
          ptr=ptr-&gt;left;
         else
        {
         ptr-&gt;left=newptr;
         newptr-&gt;parent=ptr;
         break;
        }
      } 
       else
      {
        if(ptr-&gt;right!=NULL)
         ptr=ptr-&gt;right;
        else
       {
         ptr-&gt;right=newptr;
         newptr-&gt;parent=ptr;
         break;
        }
      }
     }
  
    }
  
      void deleteLeaf(node **root)
    {
  
        node *leafParent=NULL;
  
        if((*root)-&gt;left!=NULL)
         deleteLeaf(&amp;((*root)-&gt;left));
  
        if((*root)-&gt;right!=NULL)
         deleteLeaf(&amp;((*root)-&gt;right));
  
  
        if((*root)-&gt;left==NULL &amp;&amp; (*root)-&gt;right==NULL)
       {
  
        /*  leafParent=(*root)-&gt;parent;
  
            if(leafParent-&gt;left==(*root))
             leafParent-&gt;left=NULL;
            else
             leafParent-&gt;right=NULL;
        */
  
            free(*root);
          }
        }
  
   void inorder(node *root)
  {
    if(root-&gt;left!=NULL)
     inorder(root-&gt;left);
  
    printf(" %d ", root-&gt;data);
  
    if(root-&gt;right!=NULL)
     inorder(root-&gt;right);
  }
  
   main()
  {
   node *root=NULL;
   int i,n,val;
  
   printf("\n How many elements ?");
   scanf("%d",&amp;n);
  
   for(i=0;i&lt;n;++i)
  {
   scanf("%d",&amp;val);
   insert(&amp;root,val);
  
  }
  
   printf("\n Inorder traversal : ");
   inorder(root);
  
   deleteLeaf(&amp;root);
   printf("\n Inorder traversal : ");
   inorder(root);
  }
  </code></pre>