I have a BinarySearchTree that consists of nodes which are both a template class of dataType student, where student is a class with private variables of name and grade.
At the moment I can print the tree, find names and or grades in the tree but I am having trouble deleting nodes from the tree.
I am trying to delete all students who had a grade < 50 (so failed).
Once a node is deleted one of the following needs to occur:
- Left child is empty: Replace the node by its right child.
- Left child is not empty: Replace the node by the highest element in the left
branch.
My understanding of this is, if this was the tree:
1
/ \
2 3
/ \ /\
4 5 6 7
If 2 failed i.e. had a grade < 50
You would end up with
1
/ \
4 3
\ / \
5 6 7
4 being the highest element in the left branch.
If this was the tree:
1
/ \
2 3
\ / \
5 6 7
and 2 failed
you would end up with
1
/ \
5 3
/ \
6 7
If this was the tree:
1
/ \
2 3
/ \ / \
4 5 6 7
and 1 failed
you would end up with
5
/ \
2 3
/ / \
4 6 7
I have been having a lot of trouble trying to create functions to do this, at the moment I have:
void checkBranch() //called from main - used to pass the root node to checkBranch()
{
checkBranch(studentTree.getRoot());
}
bool checkBranch(BTNode<Student>* currentNode)
{
if (currentNode != NULL)
{
if (checkBranch(currentNode -> getLeft()))
{
deleteNode(currentNode, true);
}
if (checkBranch(currentNode -> getRight()))
{
deleteNode(currentNode, false);
}
return (currentNode -> getData().getGrade() < 50.0);
}
else
{
return false;
}
}
Now I am trying to add the deleteNode function where I am just stuck on what to do / handle what needs to occur:
void deleteNode(BTNode<Student> *parentNode, bool left)
{
BTNode<Student>* nodeToDelete;
if (left)
{
nodeToDelete = parentNode->getLeft();
}
}
I managed to achieve it with this: