#include <stdio.h>

enum { stack_len = 1024 };

enum state {
    start,
    left_visited,
    completed
};

struct node {
    int val;
    struct node *left, *right;
};

struct stack {
    const struct node *p;
    enum state st;
};

void stack_push(struct stack *s, int *size,
                const struct node *p, const enum state st)
{
    struct stack *tmp = &s[*size];
    (*size)++;
    tmp->p = p;
    tmp->st = st;
}

void stack_pop(int *size)
{
    (*size)--;
}

void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
    struct node *tmp = &nodes[*nodes_used];
    (*nodes_used)++;
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
    if (!*p)
        tree_push(p, nodes, nodes_used, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, nodes, nodes_used, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, nodes, nodes_used, val);
}

void tree_print1(const struct node *p)
{
    if (!p)
        return;
    tree_print1(p->left);
    printf("%d ", p->val);
    tree_print1(p->right);
}

void tree_print(const struct node *p)
{
    struct stack backpath[stack_len], *s;
    int size = 0;
    stack_push(backpath, &size, p, start);
    while (size) {
        s = &backpath[size - 1];
        switch (s->st) {
            case start:
                s->st = left_visited;
                if (s->p->left)
                    stack_push(backpath, &size, s->p->left, start);
                break;
            case left_visited:
                printf("%d ", s->p->val);
                s->st = completed;
                if (s->p->right)
                    stack_push(backpath, &size, s->p->right, start);
                break;
            case completed:
                stack_pop(&size);
        }
    }
}

int main()
{
    struct node *p, nodes[stack_len];
    int nodes_used = 0;

    p = NULL;
    tree_insert(&p, nodes, &nodes_used, 1);
    tree_insert(&p, nodes, &nodes_used, 3);
    tree_insert(&p, nodes, &nodes_used, 2);
    tree_print(p);
    printf("\n");

    return 0;
}
