Binary Search Tree Delete function issue
Dec 7, 2016 at 12:50am UTC
I am unable to get my delete function (or my delete all function which im guessing is the same issue) to work on my binary search tree. I need to check to see if there are any children: 1,2 or 0.
Delete Function:
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 58 59 60
void Delete(T key)
{
cout << " DELETE FUNCTION " << endl;
//find node to delete
BSTNode<T> *deleteNode = Find(key);
cout << " Deleting: " ;
cout << deleteNode -> key << endl;
//BSTNode<T> *deleteNode = root;
while (deleteNode)
{
if (deleteNode -> key == key)
return ;
else if (key < deleteNode -> key)
{
deleteNode = deleteNode -> left;
}
else
{
deleteNode = deleteNode -> left;
}
}
//temp ptr to reattach left
BSTNode<T> *tempNodePtr = nullptr ;
if (deleteNode == nullptr )
{
cout << " Cannot delete empty node! " << endl;
}
else if (deleteNode -> right == nullptr )
{
tempNodePtr = deleteNode;
//Reattach left side
deleteNode = deleteNode -> left;
delete tempNodePtr;
}
else if (deleteNode -> left == 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)
{
//reattach left subtree
tempNodePtr -> left = deleteNode -> left;
tempNodePtr = deleteNode;
//reattach right subtree
deleteNode = deleteNode -> right;
delete tempNodePtr;
}
}
}
Delete All Function:
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
//********************
//Remove All function*
//********************
void DeleteAll()
{
DeleteAll_Helper(root);
root = NULL;
BSTNode<T> *rootPtr;// = nullptr;
rootPtr = root;
if (rootPtr == nullptr )
{
cout << " There is no tree! " << endl;
}
}
//******************
//Delete All Helper*
//******************
void DeleteAll_Helper(BSTNode<T> *rootPtr)
{
//cout << " DELETE HELPER FUNCTION. " << endl;
if (!rootPtr)
{
cout << "Not root" << endl;
return ;
}
else
{
if (rootPtr -> left) // visit the left sub-tree,
{
DeleteAll_Helper(rootPtr -> left);
if (rootPtr -> left == nullptr && rootPtr -> right == nullptr )
{
cout << "deleting: " << rootPtr -> key << endl;
delete rootPtr;
}
}
if (rootPtr -> right) // visit the right sub-tree,
{
DeleteAll_Helper(rootPtr -> right);
if (rootPtr -> left == nullptr && rootPtr -> right == nullptr )
{
cout << "deleting: " << rootPtr -> key << endl;
delete rootPtr;
}
}
return ;
}
}
};
Topic archived. No new replies allowed.