Binary Search Tree Delete function issue
Dec 11, 2016 at 8:44pm UTC
I am unable to get my binary tree to delete the node properly. It doesnt always find the delete key (even if its there) and i get a memory error when run the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
//****************
//Delete Function*
//****************
void Delete(T key)
{
cout << " DELETE FUNCTION " << endl;
//find node to delete
BSTNode<T> *deleteNode = Find(key);
cout << " Deleting The Following: " ;
cout << deleteNode -> key << endl;
//BSTNode<T> *nodeIndex = root;
//temp ptr to reattach left
BSTNode<T> *tempNodePtr = nullptr ;
if (deleteNode == nullptr )
{
cout << " Cannot delete empty node! " << endl;
}
else if (deleteNode -> right == nullptr && deleteNode -> left == nullptr )
{
cout << "deleteing leaf node. " << endl;
delete deleteNode;
}
else if (deleteNode -> right == nullptr )// && deleteNode -> left != nullptr)
{
tempNodePtr = deleteNode;
//Reattach left side
deleteNode = deleteNode -> left;
delete tempNodePtr;
}
else if (deleteNode -> left == nullptr )// && deleteNode -> right != nullptr)
{
tempNodePtr = deleteNode;
//Reattach right side
deleteNode = deleteNode -> right;
delete tempNodePtr;
}
//if node has two kids
else
{
//Move one node to right
tempNodePtr = deleteNode -> right;
//move to end of left node
while (tempNodePtr -> left)
{
tempNodePtr = tempNodePtr -> left;
}
//reattach left subtree
tempNodePtr -> left = deleteNode -> left;
tempNodePtr = deleteNode;
//reattach right subtree
deleteNode = deleteNode -> right;
delete tempNodePtr;
}
delete deleteNode; // <--- without this code the node wont delete
}
Last edited on Dec 11, 2016 at 8:47pm UTC
Topic archived. No new replies allowed.