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

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

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);
}

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

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");

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

    return 0;
}
