Been working on this for a while. There is a segmentation fault around the case where there are two child nodes. I'm not sure how to fix the problem. I'm pretty sure the other cases are correct but I am currently struggling with the case where the node to be deleted has 2 child nodes.
bool BinarySearchTree::remove(BinarySearchTree::TaskItem val)
if(!exists(val))
return false;
else{
TaskItem* cur = root;
TaskItem* parent = nullptr;
if(size == 1){ // only one node in tree
delete cur;
root = nullptr;
size--;
return true;
}
else if(*cur == val && (!cur->right || !cur->left)){// root node is target, with one child node
if(!cur->right){
root = cur->left;
delete cur;
}
else{
root = cur->right;
delete cur;
}
size--;
return true;
}
while(!(*cur==val)){
if(val.priority < cur->priority){
parent = cur;
cur = cur->left;
}
else{
parent = cur;
cur = cur->right;
}
}
if(!cur->right && !cur->left){ // no child nodes
if(parent->right == cur){
parent->right = nullptr;
delete cur;
}
else{
parent->left = nullptr;
delete cur;
}
}
else if(cur->right && cur->left){ // 2 child nodes
TaskItem* success = cur->right;
TaskItem* par_success = cur;
while(!success->left){
par_success = success;
success = success->left;
}
cur->priority = success->priority;
cur->description = success->description;
if(par_success->left == success){
par_success->left = nullptr;
}
else{
par_success->right = nullptr;
}
delete success;
}
else{// one child node
if(!cur->right){ // child node on the left
if(parent->right == cur){
parent->right = cur->left;
delete cur;
}
else{
parent->left = cur->left;
delete cur;
}
}
if(!cur->left){
if(parent->right == cur){
parent->right = cur->right;
delete cur;
}
else{
parent->left = cur->right;
delete cur;
}
}
}
size--;
return true;
}
} ```
Aucun commentaire:
Enregistrer un commentaire