Hey Im writing a binary tree in c++ and have some problems with removing all nodes. I tried to use the following function for that:
void RemoveAll() { RemoveAll(Root); }
void RemoveAll(Node *node)
{
if (!node) return;
RemoveAll(node->Left);
RemoveAll(node->Right);
delete node;
}
And my printing functions:
void PreOrder() { PreOrder(Root); }
void PreOrder(Node *node)
{
if (!node) return;
std::cout << node->Element << std::endl;
PreOrder(node->Left);
PreOrder(node->Right);
}
void InOrder() { InOrder(Root); }
void InOrder(Node *node)
{
if (!node) return;
InOrder(node->Left);
std::cout << node->Element << std::endl;
InOrder(node->Right);
}
void PostOrder() { PostOrder(Root); }
void PostOrder(Node *node)
{
if (!node) return;
PostOrder(node->Left);
PostOrder(node->Right);
std::cout << node->Element << std::endl;
}
The problem is that if I run a printing function afterwards to see if the nodes are really deleted I get an Exception which tells me that the given node was 0xFFFFFFFFFFFFFFF7
. Any ideas why? Thanks in advance.
Thanks to Jarod42 and 0x499602D2 who provided the answer.
The final solution looks like this for all future users who have the same problem:
void RemoveAll() { RemoveAll(Root); }
void RemoveAll(Node *&node)
{
if (!node) return;
RemoveAll(node->Left);
RemoveAll(node->Right);
delete node;
node = nullptr;
}