0

I have problem with delete node function in BST. I tested all other function works fine but if i print tree after deleting an node it causes segmentation fault.
Here is my code for deletion:

struct Tree * findinorder (struct Tree *t)
{
   while (t->lchild != NULL)
         t=t->lchild;
   return t;       
}

bool deleteNode (struct Tree *t, int fvalue)
{
 bool find = false; //this is to check if node is already found don't go to right sub tree
 struct Tree *inorder;
 if (t==NULL) return find;
 if (t->value == fvalue)
 {
    if (t->lchild == NULL && t->rchild == NULL )
    {
       free(t);
    }
    else {
         if (t->lchild ==NULL)
            t= t->rchild;
         else {
            if (t->rchild ==NULL)
               t= t->lchild;
            else {
                       inorder = findinorder(t->rchild);
                       t->value = inorder->value;
                       free(inorder);
            }
         }
    }
    return true;
 }
 find = deleteNode(t->lchild, fvalue);
 if (!find)
    find = deleteNode(t->rchild, fvalue);
 return find;   
}

here is tree structure and function for printing:

struct Tree
{
   int value;
   struct Tree *lchild;
   struct Tree *rchild;       
}*root;

void print (struct Tree *t)
{
    if (!t) return;
    if(t->lchild != NULL)
                 print(t->lchild);  

    printf("%d\n",t->value);             

    if(t->rchild != NULL)
                 print(t->rchild);
}

My suspect is some how node is not set to null which causing problem in print and it goes on.
Please help.

Abhi
  • 192
  • 1
  • 4
  • 17

1 Answers1

0

You should keep a pointer to the previous node so that you can update the new references to rchild / lchild accordingly:

enter image description here

imagine node to be a pointer to 5, the removal (in this concrete case) should look more like:

if (node->rchild && node->rchild->value == 21) {
    struct Tree *child = node->rchild;
    node->rchild = child->rchild;             // <-- update reference
    free(child);
}

But look at the node 21 and think of what should happen upon its removal? ...The code should be more complex than just calling free on a pointer to node once it is found :)

What happens in your case is that you free the appropriate node, but once you traverse it after that, the pointer to the node that has previously been freed is used, which yields undefined behavior.

LihO
  • 41,190
  • 11
  • 99
  • 167