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

enum state {
    start,
    left_visited,
    completed
};

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

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

void stack_push(struct stack **s, const struct node *p, const enum state st)
{
    struct stack *tmp = malloc(sizeof(*tmp));
    tmp->p = p;
    tmp->st = st;
    tmp->next = *s;
    *s = tmp;
}

void stack_pop(struct stack **s)
{
    struct stack *tmp = *s;
    *s = (*s)->next;
    free(tmp);
}

void tree_push(struct node **p, int val)
{
    struct node *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, int val)
{
    if (!*p)
        tree_push(p, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, 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 *s;
    s = NULL;
    stack_push(&s, p, start);
    while (s)
        switch (s->st) {
            case start:
                s->st = left_visited;
                if (s->p->left)
                    stack_push(&s, s->p->left, start);
                break;
            case left_visited:
                printf("%d ", s->p->val);
                s->st = completed;
                if (s->p->right)
                    stack_push(&s, s->p->right, start);
                break;
            case completed:
                stack_pop(&s);
        }
}

int main()
{
    struct node *p;

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

    return 0;
}
