/* to an in-order traversal of a binary tree, writing the number in */
/* each node out to disk */

#include <stdio.h>

struct tree_node
{
    int num;
    struct tree_node *left, *right;
};

struct tree_node *create_tree_node(int);
void write_tree_to_file(struct tree_node *, char *);
void traverse_tree_and_write(struct tree_node *, FILE *);

main()
{
    struct tree_node *tree;
    
    /* build a dummy tree for illustrative purposes */
    
    tree = create_tree_node(4);

    tree->left = create_tree_node(2);
    tree->left->left = create_tree_node(1);
    tree->left->right = create_tree_node(3);

    tree->right = create_tree_node(6);
    tree->right->left = create_tree_node(5);
    tree->right->right = create_tree_node(8);
    tree->right->right->left = create_tree_node(7);

    write_tree_to_file(tree, "treefile.txt");
}

struct tree_node *
create_tree_node(int num)
{
    struct tree_node *node;

    node = (struct tree_node *) malloc(sizeof(*node));
    
    node->num = num;
    node->left = node->right = NULL;

    return node;
}

void
write_tree_to_file(struct tree_node *tree, char *filename)
{
    FILE *fp;
    
    if (!tree)
    {
        fprintf(stderr, "Error: write_tree_to_file passed NULL tree argument!\n");
        exit(-1);
    }

    if (!filename)
    {
        fprintf(stderr, "Error: write_tree_to_file passed NULL filename argument!\n");
        exit(-2);
    }

    fp = fopen(filename, "w");

    if (!fp)
    {
        fprintf(stderr, "Error: can't open %s for writing\n",
                filename);
        exit(-3);
    }

    traverse_tree_and_write(tree, fp);

    fclose(fp);
}

void
traverse_tree_and_write(struct tree_node *tree, FILE *fp)
{
    if (!tree) return;

    if (tree->left) traverse_tree_and_write(tree->left, fp);
    fprintf(fp, "%d\n", tree->num);
    if (tree->right) traverse_tree_and_write(tree->right, fp);
}
