void Bst_DeleteStudent(struct BstStudent** root, char student_name[]){
struct BstStudent* current = *root;
struct BstStudent* parent = NULL;
int flag = 0;
int i;
while(current != NULL){
if(strcmp(current->name, student_name) > 0){
parent = current;
current = current->left;
}
else if(strcmp(current->name, student_name) < 0){
parent = current;
current = current->right;
}
else{
flag = 1;
//If node has no children
if(current->left == NULL && current->right == NULL){
if(parent->left == current){
parent->left = NULL;
}
else{
parent->right = NULL;
}
free(current);
return;
}
//If current has one child
else if((current->left == NULL && current->right != NULL) || (current->left != NULL && current->right == NULL)){
//If node has a right child
if(current->right != NULL && current->left != NULL){
if(parent->right == current){
parent->right = current->right;
}
else if(parent->left == current){
parent->left = current->right;
}
}
//If node has a left child
else if(current->left != NULL && current->right == NULL){
if(parent->right == current){
parent->right = current->left;
}
else if(parent->left == current){
parent->left = current->left;
}
}
free(current);
return;
}
//If current has two children
else{
struct BstStudent* swap_this = current->right;
struct BstStudent* swap_this_prev = current;
while(swap_this->left != NULL){
swap_this_prev = swap_this;
swap_this = swap_this->left;
}
strcpy(current->name, swap_this->name);
current->id = swap_this->id;
for(i=0; i<5; i++){
current->marks[i] = swap_this->marks[i];
}
if(swap_this_prev->left == swap_this){
swap_this_prev->left = swap_this->right;
}
else if(swap_this_prev->right == swap_this){
swap_this_prev->right = swap_this->right;
}
free(swap_this);
return;
}
}
}
if(flag == 1){
printf("\nStudent named '%s' removed\n", student_name);
}
else{
printf("\nNo student named '%s' is found in the list!\n", student_name);
}
}
Hi guys, I'm currently want to make a delete function for a binary search tree implementation which sorts the nodes based on names, alphabetically. My code works perfectly fine can delete most of the time. The code only gives a segmentation fault in a specific case when I want to delete the root node and the root node has only one child or no children. Every other deletion works. Can you guys please help me?
You are trying to access the left/right node of NULL(parent), in the case of deletion of root node.
Add a condition before accessing parent whether parent is NULL or not if parent is not NULL then only assign the value to its node pointer.
For example
Add the same condition in other parts of code also.