I have to implement a binary search tree using C++ for one of assignments. I’ve created the class, and attempted to implement the InsertItem, PrintTree, DeleteTree methods for the class, I think I did everything right but for some reason my program keeps crashing 🙁
Here’s my code:
PrintTree Method
template <class TItem>
void BinarySearchTree<TItem>::PrintTree()
{
PrintTree(RootNode);
}
template <class TItem>
void BinarySearchTree<TItem>::PrintTree(BinarySearchTreeNode* Node)
{
if(Node == NULL)
return;
cout << Node->Data << endl;
PrintTree(Node->LeftChild);
PrintTree(Node->RightChild);
}
DeleteTree Method
template <class TItem>
void BinarySearchTree<TItem>::DeleteTree()
{
DeleteTree(RootNode);
}
template <class TItem>
void BinarySearchTree<TItem>::DeleteTree(BinarySearchTreeNode* Node)
{
if(Node == NULL)
return;
DeleteTree(Node->LeftChild);
DeleteTree(Node->RightChild);
delete Node;
}
My sequence of method calls up until the program crashes:
I insert items F,B,G,A,D,I,C,E,H: works fine
I call PrintTree(): works fine
I call DeleteTree(): works fine
I call PrintTree() again: program crashes
For some reason the expression if(RootNode == NULL) is not returning true after the DeleteTree() method is called, so the program tries to print something that doesn’t exist and crashes. I’m not sure why this is happening, what am I doing wrong here?
Any and all help is appreciated.
Calling “delete” does not null out the pointer.
You will want to do:
EDIT:
Pass the pointer by address so that you can clean up dangling pointers as you go: