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

#include "tree.h"

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_print(const struct node *p)
{
    if (!p)
        return;
    tree_print(p->left);
    printf("%d ", p->val);
    tree_print(p->right);
}

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

const struct node *stack_pop(struct stack **s)
{
    struct stack *tmp = *s;
    const struct node *p = tmp->p;
    *s = (*s)->next;
    free(tmp);
    return p;
}

void stack_init1(struct stack1 *s, int capacity)
{
    s->p = malloc(capacity * sizeof(*s->p));
    s->capacity = capacity;
    s->size = 0;
}

void stack_push1(struct stack1 *s, const struct node *p)
{
    if (s->size == s->capacity) {
        s->capacity *= 2;
        s->p = realloc(s->p, s->capacity * sizeof(*s->p));
    }
    s->p[s->size] = p;
    s->size++;
}

const struct node *stack_pop1(struct stack1 *s)
{
    s->size--;
    return s->p[s->size];
}
