didn't think of that one.... i came up with changing the functions to take Bin_Node and passing tree-> root instead of tree
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct Bin_Node
{
int data;
struct Bin_Node *left;
struct Bin_Node *right;
}Bin_Node;
typedef struct Bin_Tree
{
struct Bin_Node *root; //same as head node in a linked list
int node_count;
}Bin_Tree;
Bin_Tree *create_tree(void);
Bin_Tree *initalize_tree(Bin_Tree *tree);
Bin_Node *create_node(void);
Bin_Node *initalize_node(Bin_Node *node, int data);
void insert_node(Bin_Node **tree, Bin_Node *node);
void print_tree(const Bin_Node *tree);
void destroy_tree(Bin_Node *tree);
int main()
{
int i, nums[] = {2, 6, 3, 9, 20, 13, 54, 10, 43};
Bin_Tree *tree;
Bin_Node *node;
tree = create_tree();
assert(tree != NULL);
tree = initalize_tree(tree);
for (i = 0; i < 9; i++)
{
node = create_node();
assert(node != NULL);
node = initalize_node(node, nums[i]);
insert_node(&tree->root, node);
tree->node_count++;
}
print_tree(tree->root);
destroy_tree(tree->root);
return 0;
}
Bin_Tree *create_tree(void)
{
return malloc(sizeof(Bin_Tree));
}
Bin_Tree *initalize_tree(Bin_Tree *tree)
{
tree->node_count = 0;
tree->root = NULL;
return tree;
}
Bin_Node *create_node(void)
{
return malloc(sizeof(Bin_Node));
}
Bin_Node *initalize_node(Bin_Node *node, int data)
{
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void insert_node(Bin_Node **tree, Bin_Node *node)
{
if (!*tree) //parent node has no children??
{
*tree = node;
printf("node inserted\n");
}
else
{
if ((*tree)->data < node->data) //the data of the parent we are looking at is less than the data of the node so go to its right child
{
insert_node(&(*tree)->right, node);
}
else
{
insert_node(&(*tree)->left, node);
}
}
}
void print_tree(const Bin_Node *tree)
{
if (!tree)
{
return;
}
if (tree->left) //parent node has a child to the left
{
print_tree(tree->left);
}
printf("node data = %d\n", tree->data);
if (tree->right) //parent node has a child to the right
{
print_tree(tree->right);
}
}
void destroy_tree(Bin_Node *tree)
{
if (tree) //parent has children
{
destroy_tree(tree->left);
destroy_tree(tree->right);
free(tree);
printf("node deleated\n");
}
}
this now works with the expected results however it raises a couple of questions
i have been told never write &*x as the two operands cancel each other out however i "have" to do that in the insert function if one argues that the & only cancels one * out then why cant i write *tree instead as an argument.
2nd question is in the tutorial i found in here line 119 should be if (!tree) but that didn't work is my delete function correct.
coop