this is the code so far copied from the book with a couple of slight changes
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Bin_Node
{
int data;
struct Bin_Node *left; //pointer to left sub tree
struct Bin_Node *right; //pointer to right sub tree
}Bin_Node;
typedef struct Bin_Tree
{
struct Bin_Node *root; // same as a list haveing a pointer to head
int node_count; // number of nodes in the tree.
}Bin_Tree;
Bin_Tree *create_tree(void);
int search_tree(const Bin_Tree *tree, int item);
int insert_node(Bin_Tree *tree, int item);
int main()
{
return 0;
}
Bin_Tree *create_tree(void) //create the root node
{
Bin_Tree *tree = malloc(sizeof(*tree));
if (!tree) // test if malloc returned a null pointer
{
return NULL;
}
tree->root = NULL;
tree->node_count = 0;
return tree;
}
int search_tree(const Bin_Tree *tree, int item)
{
const Bin_Node *node;
if (!tree)
{
printf("no tree created\n");
return -1;
}
node = tree->root;
for(;;)
{ //try writing this with no else if statements in future testing
if (!node) // tree is empty
{
return 0;
}
else if (item == node->data) //item value already exists
{
return 1;
}
else if (item > node->data)// item value is greater than the value of node
{
node = node->right; //go to the nodes right child
}
else //item value is less than the value of node
{
node = node->left; // go to the nodes left child
}
}
}
int insert_node(Bin_Tree *tree, int item)
{
Bin_Node *node, **new_node;//changed new to new_node as new is a keyword
if (!tree)
{
printf("no tree created\n");
return -1;
}
new_node = &tree->root;
node = tree->root;
for (;;)
{
if (!node) //tree is empty
{
node = *new_node = malloc(sizeof(*node));
if (node)
{
node->data = item; // assign the value of item to data member
node->left = node->right = NULL;
tree->node_count++;
return 1;
}
else
{
return 0;
}
}
else if(item == node->data)
{
return 2;
}
else if (item > node->data);
{
new_node = &node->right;
node = node->right;
}
else
{
new_node = &node->left;
node = node->left;
}
}
}
changes i have made is to the names of the functions as they mean more to me than bin_insert for example. lines 45 - 49 and 77 - 81 the code in the book uses
Code:
assert (tree != NULL)
i can never get the assert to work as the book is fairly old (pre c99) i assume it was something taken out
i have also shortened
Code:
if (node == null)
//to
if (!node)
//same with testing for node != null
the final change is line 90 the book says
Code:
Bin_Node *node, **new
i changed new to new_node as new is a keyword.
the book explains that it uses **new_node to point to the pointer that we followed to arrive at node
onto the issues i have with this code. can line 90 (and 94 for that matter) be written as
Code:
node = malloc(sizeof(*node));
*new_node = malloc(sizeof(*node));
if so should they be written like that
the next issue is it doesn't make use of new_node anywhere with in the block of code controlled by if (!node)
coop