I've actually created a successful Bin-search-tree in a single file.
However, I'm trying to layer my code so that one file has a node type, the second a binary tree with a node type etc.
Now, so far I've been successful in creating all other functions, other than inorder traversing.
This is the working code in my single face implementation of a bin-search-tree.
Code:
void inorder(node *temp)
{
if (temp != NULL)
{
inorder(temp->left_child);
printf("%d\t", temp->data);
inorder(temp->right_child);
}
}
Now, for my new modulated code I have this:
Code:
#include "bin_search_tree.h"
#include <string.h>
struct Binary_search_tree
{
node *root;
};
b_s_tree *binary_search_tree_init(int value)
{
b_s_tree *temp = malloc(sizeof(*temp));
if (!temp)
{
fprintf(stderr, "error allocating memory for tree\n");
exit(EXIT_FAILURE);
}
temp->root = node_init(value);
return temp;
}
void insert(b_s_tree *tree, int key)
{
node *new_node;
b_s_tree *temp;
if (key > get_node_key(tree->root))
{
if (get_node_right(tree->root) == NULL)
{
new_node = node_init(key);
link_right_node(tree->root, new_node);
}
else
{
memcpy(temp, tree, sizeof(*temp));
temp->root = get_node_right(tree->root);
insert(temp, key);
}
}
if (key < get_node_key(tree->root))
{
if (get_node_left(tree->root) == NULL)
{
new_node = node_init(key);
link_left_node(tree->root, new_node);
}
else
{
memcpy(temp, tree, sizeof(*temp));
temp->root = get_node_left(tree->root);
insert(temp, key);
}
}
}
void inorder(b_s_tree *tree)
{
b_s_tree *left;
b_s_tree *right;
memcpy(left, tree, sizeof(*left));
memcpy(right, tree, sizeof(*right));
if (tree->root != NULL)
{
left->root = get_node_left(left->root);
inorder(left);
printf("%d\t", get_node_key(left->root));
printf("%d\t", get_node_key(right->root));
right->root = get_node_right(right->root);
inorder(right);
}
}
The issue function is:
Code:
void inorder(b_s_tree *tree)
{
b_s_tree *left;
b_s_tree *right;
memcpy(left, tree, sizeof(*left));
memcpy(right, tree, sizeof(*right));
if (tree->root != NULL)
{
left->root = get_node_left(left->root);
inorder(left);
printf("%d\t", get_node_key(left->root));
printf("%d\t", get_node_key(right->root));
right->root = get_node_right(right->root);
inorder(right);
}
}
I know it isn't pretty, but for now that's fine.. just learning.. This code gives me a Segmentation fault: 11..
I have got it to work using iteration, and if I changed b_s_tree for Node it works fine with recursion (which is what I want it to do with a b_s_tree type).
Any ideas on how to get this working?
The only solution I could do, although it feels wrong, is to pass the node from inorder() to another function that does recursion on an actually node (like the first example), that would ensure that the driver couldn't go anywhere near a 'node', but there must be an easier way.