BST segmentation fault when deleting the root node

  c++, data-structures

I’m currently trying to implement a BST, though I ran into trouble trying to implement the deletion function. The function gives a segfault when the node its trying to delete is the root node. Deleting nodes other than the root node doesn’t seem to cause this problem. Any help?

bool bst::del(int num) { //return if successfully deleted a node
  treenode *del_node = root;
  treenode *par_node = NULL;
  while (del_node) {
    if (del_node->key == num) break;
    par_node = del_node;
    (del_node->key > num)?
    del_node = del_node->lsub:
    del_node = del_node->rsub;
  }

  //node not found
  if (!del_node) return 0;

  //2 children
  if (del_node->lsub && del_node->rsub) { 
    //swap to deleting replacement
    //replace = max in lsub || min in rsub
    treenode *replace = del_node->lsub;
    while (replace->rsub) {
      par_node = replace;
      replace = replace->rsub;
    }
    *del_node = *replace;
    del_node = replace;
  }

  //0 child
  if (!del_node->lsub && !del_node->rsub) { 
    (par_node->key > num)?
    par_node->lsub = NULL:
    par_node->rsub = NULL;
  }

  //1 child
  else if (del_node->lsub) {
    (par_node->key > num)?
    par_node->lsub = del_node->lsub:
    par_node->rsub = del_node->lsub;
  } else {
    (par_node->key > num)?
    par_node->lsub = del_node->rsub:
    par_node->rsub = del_node->rsub;
  }
  delete del_node;
  return 1;
}```

Source: Windows Questions C++

LEAVE A COMMENT