I have this deletion code that doesn't fully work, and I have no idea how to fix it:
Code:
bool BINARYTREE::deleteByNode(BNODE* nodePtr) {
bool ret = false;
if (nodePtr != NULL)
{
if (nodePtr->isLeaf())
{
if (parent != NULL)
{
if (parent->getLeft() == nodePtr)
parent->setLeft(NULL);
else
parent->setRight(NULL);
}
delete nodePtr;
if (nodePtr == root)
root = NULL;
ret = true;
} else {
if (nodePtr->getLeft())
{
BNODE* temp = nodePtr->getLeft();
BNODE* tempParent = nodePtr;
while(temp->getRight()!= NULL)
{
tempParent = temp;
temp = temp->getRight();
}
nodePtr->setData(temp->getData());
ret = true;
if(temp->getData() > tempParent->getData())
{
tempParent->setRight(NULL);
tempParent->setLeft(temp->getLeft());
}
else
tempParent->setLeft(NULL);
delete temp;
} else {
nodePtr->setData(nodePtr->getRight()->getData());
ret = true;
parent = nodePtr;
deleteByNode(nodePtr->getRight());
}
}
}
return(ret);
}
This code works with some trees like: 1, 3, 32, -1
but with a tree like 1, 0, -2
it crashes :'( because every node is the the left of every other node.
If anyone can help I'd appreciate it. I'm not usre about the attachment rules, but if you downloadthe attachment, just rename it to a .zip extension and unzip it to get all of my code. I'm sorry if this violates any rules.
Thanks,
Sean