Delete all from a Binary Tree
Hi to all.
I'm new to this board (and to C code) but have gone through some of the tutorials of the site and searched the board for relevant tips to my problem.
I'm trying to write an implemenation of an unbalanced binary search tree. I have most of the basic functions working like create tree, attach new nodes, search and tree traversal in pre-order form. I'm trying to write a delete function that deletes all nodes including the root if necessary. The same function will be used to delete whole branches of the tree also. I am passing the killTree function a node and the code is something like this:
Code:
typedef struct Node NODE;
// Global variables.
HANDLE gHeap;
NODE* gRoot; // the root node
NODE* tempN;
// Node is a Struct containing 3 members.
struct Node
{
int valKey; // holds the node's data or key
struct Node* Left; // pointer to left subtree
struct Node* Right; // pointer to left subtree
};
other code.......
void killTree(NODE* kNode)
{
if (kNode->Left != NULL)
{
killTree(kNode->Left);
}
if (kNode->Right != NULL)
{
killTree(kNode->Right);
}
if (kNode != NULL)
{
HeapFree(gHeap, 0, kNode);
}
}
void destroyMemory()
{
HeapDestroy(gHeap);
gHeap = NULL;
gRoot = NULL;
}
void PrintRoot(NODE* gRoot)
{
if (gRoot == NULL)
{
printf ("The root of the tree is:%i\n",gRoot->valKey);
}
}
When debugging with line by line I get an access violation error with Dev-C++ and a SIGSEV with Code::Blocks after running through all the code and try to print the root again to see if the funciton has worked. I tried the latter as I was noticing the CPU going to 98% after a few runs of the program and thought it could be some problem due to the awful code I'm writing.
I am calling the deleteTree function with deleteTree(gRoot) and then destroyMemory().
This code will be sort of temporary as in the end it will be compiled as a DLL exposing the functions to a C# "frontend".
Any form of help or tips of how to go about doing this would be greatly appreciated. Thanks.