I have a question... If I have a Binarytree like this:
typedef struct
{
char* text;
char* line;
struct Node* left;
struct Node* right;
}Node
and have a start function:
Node *start(Node* ptr)
{
if(ptr == NULL)
{
ptr = (Node*)malloc(sizeof(Node));
ptr->text = "some text";
ptr->line = "another text";
ptr->left = NULL;
ptr->right = NULL;
}
return (ptr);
}
And a funtion to add left child in binarytree, if root is not empty and here I must give my text and line dynamic memory.
Node* addNode(Node* ptr)
{
if(ptr != NULL)
{
Node* leftNode = (Node*)malloc(sizeof(zeiger));
char* text = (char*) malloc(100*sizeof(char));
char* line = (char*) malloc(100*sizeof(char));
line = "some text 2";
text = "another text";
if(leftNode !=NULL)
{
leftNode->text = text;
leftNode->line = line;
leftNode->right = NULL;
ptr->left = leftNode;
}
return leftNode;
}
return ptr;
}
Now the problem ist I want to free everything in tree so I have a a function like this to call himself if left or right or root is not NULL. So i saw some codes that I should free the root and not the datas.
void freeTree(Node* root)
{
while(1)
{
if(root == NULL)
{
break;
}
else if (root->left != NULL)
{
freeTree(root->left);
root->left = NULL;
}
else if (root->right) {
freeTree(root->right);
root->right = NULL;
}
else
{
free(root);
}
}
}
Main.c
int main(int argc, char const *argv[]) {
Node* root = NULL;
root = start(root);
root = addNode(root);
freeTree(root);
return 0;
}