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

enum states { LEFT, CENTER, RIGHT };

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

struct task {
    struct node *p;
    enum states state;
    struct task *next;
};

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

void push_list(struct task **t, struct node *p, enum states state) {
    struct task *tmp;
    tmp = malloc(sizeof *tmp);
    tmp->p = p;
    tmp->state = state;
    tmp->next = *t;
    *t = tmp;
}

void pop_list(struct task **t, struct node **p) {
    struct task *tmp;
    tmp = *t;
    *p = (*t)->p;
    *t = (*t)->next;
    free(tmp);
}

struct node **search_tree(struct node **r, int val) {
    while (*r) {
        if ((*r)->val == val)
            return r;
        else if (val < (*r)->val)
            r = &(*r)->left;
        else if (val > (*r)->val)
            r = &(*r)->right;
    }
    return r;
}

int insert_node(struct node **r, int val) {
    struct node **pos = search_tree(r, val);
    if (!*pos) {
        init_node(pos, val);
        return 1;
    } else
        return 0;
}

/*
             27
       /            \
     18              34
   /    \         /     \
  4     21       29     39
 / \   /  \     /  \   /  \
n   n n    n   n    n n    n
*/
void print_tree(struct node *p) {
    struct task *t = NULL;
    push_list(&t, p, LEFT);
    for (int i = 1; t && i <= 20; i++) {
        switch (t->state) {
            case (LEFT):
                if (p->left) {
                    t->state = CENTER;
                    p = p->left;
                    push_list(&t, p, LEFT);
                } else {
                    pop_list(&t, &p);
                    printf("%d\n", p->val);
                }
                break;
            case (CENTER):
                p = t->p;
                if (p->right) {
                    p = p->right;
                    push_list(&t, p, RIGHT);
                } else {
                    pop_list(&t, &p);
                    printf("%d\n", p->val);
                }
                break;
            case (RIGHT):
                if (p->left) {
                    p = p->left;
                    push_list(&t, p, LEFT);
                } else {
                    pop_list(&t, &p);
                    printf("%d\n", p->val);
                }
        }
    }
}

int main() {
    struct node *r = NULL;
    insert_node(&r, 27);
    insert_node(&r, 18);
    insert_node(&r, 34);
    insert_node(&r, 4);
    insert_node(&r, 21);
    insert_node(&r, 29);
    insert_node(&r, 39);
    print_tree(r);
    return 1;
}
