#include <stdio.h>
#include <stdlib.h>

typedef enum {
    start, been, end
} states;

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

typedef struct stack_s {
    node *n;
    states state;
    struct stack_s* next;
} stack;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void stack_push(stack **p, node *n, states state)
{
    stack *tmp;
    tmp = xmalloc(sizeof(stack));
    tmp->n = n;
    tmp->state = state;
    tmp->next = *p;
    *p = tmp;
}

void stack_remove(stack **p)
{
    stack *tmp;
    tmp = *p;
    *p = (*p)->next;
    free(tmp);
}


void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

void print_tree2(node *p)
{
    stack *s = NULL;
    stack_push(&s, p, start);
    while (s) {
        switch (s->state) {
            case start:
                s->state = been;
                if (s->n->left)
                    stack_push(&s, s->n->left, start);
                break;
            case been:
                printf("%d ", s->n->value);
                s->state = end;
                if (s->n->right)
                    stack_push(&s, s->n->right, start);
                        break;
            case end:
                stack_remove(&s);
        }
    }
}



int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 7);
    node_insert(&p, 6);
    node_insert(&p, 8);
    node_insert(&p, 9);
    print_tree2(p);
    printf("\n");
    return 0;
}
