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

#include "tree.h"

int tree_sum(const struct node *p)
{
    return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}

int tree_sum_do1(const struct node *p, int sum)
{
    if (!p)
        return sum;
    sum = tree_sum_do1(p->left, sum);
    return tree_sum_do1(p->right, sum + p->val);
}

int tree_sum1(const struct node *p)
{
    return tree_sum_do1(p, 0);
}

int tree_sum_do2(const struct node *p, int sum, struct stack *s)
{
    if (!p)
        return sum;
    if (p->left)
        stack_push(&s, p->left);
    if (p->right)
        return tree_sum_do2(p->right, sum + p->val, s);
    if (s) {
        const struct node *tmp = stack_pop(&s);
        return tree_sum_do2(tmp, sum + p->val, s);
    }
    return sum + p->val;
}

int tree_sum2(const struct node *p)
{
    return tree_sum_do2(p, 0, NULL);
}

int tree_sum_do3(const struct node *p, int sum, struct stack *s)
{
    if (p) {
        stack_push(&s, p);
        return tree_sum_do3(p->left, sum, s);
    }
    if (s) {
        const struct node *tmp = stack_pop(&s);
        return tree_sum_do3(tmp->right, sum + tmp->val, s);
    }
    return sum;
}

int tree_sum3(const struct node *p)
{
    return tree_sum_do3(p, 0, NULL);
}

int tree_sum_do4(const struct node *p, int sum, struct stack1 *s)
{
    if (p) {
        stack_push1(s, p);
        return tree_sum_do4(p->left, sum, s);
    }
    if (s->size) {
        const struct node *tmp = stack_pop1(s);
        return tree_sum_do4(tmp->right, sum + tmp->val, s);
    }
    return sum;
}

int tree_sum4(const struct node *p)
{
    int sum;
    struct stack1 s;
    stack_init1(&s, 1);
    sum = tree_sum_do4(p, 0, &s);
    free(s.p);
    return sum;
}

int main()
{
    int sum;
    struct node *p;

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

    sum = tree_sum(p);
    printf("%d\n", sum);

    sum = tree_sum1(p);
    printf("%d\n", sum);

    sum = tree_sum2(p);
    printf("%d\n", sum);

    sum = tree_sum3(p);
    printf("%d\n", sum);

    sum = tree_sum4(p);
    printf("%d\n", sum);

    return 0;
}
