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

typedef struct node_s {
    int value;
    struct node_s *left, *right;
} node;

void *xmalloc(int size)
{
    void *p;
    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void node_init(node **p, int value)
{
    *p = xmalloc(sizeof(node));
    (*p)->value = value;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

node **node_search(node **p, int value)
{
    while (*p && value != (*p)->value)
        if (value < (*p)->value)
            p = &(*p)->left;
        else
            p = &(*p)->right;
    return p;
}

int node_insert(node **p, int value)
{
    node **loc = node_search(p, value);
    if (!*loc) {
        node_init(loc, value);
        return 1;
    } else
        return 0;
}

/*
             5
       /            \
     3               8
   /    \         /     \
  2      4       6       9
 / \   /  \     /  \   /  \
1   n n    n   n    7 n    10
*/

/*
             5
       /            \
     3               6
   /    \         /     \
  2      4       n       7
 / \   /  \            /  \
1   n n    n          n    9
                            \
                             10
*/

/*
             5
       /            \
     3               9
   /    \         /     \
  2      4       6      10
 / \   /  \     / \    /  \
1   n n    n   n   7  n    n
*/

int node_count(node *p, int is_right)
{
    int i;
    for (i = 0; p; i++)
        if (is_right)
            p = p->left;
        else
            p = p->right;
    return i;
}

void node_remove(node **p, int value)
{
    int left_n, right_n;
    node *tmp;
    tmp = *p;
    left_n = node_count(tmp, 0);
    right_n = node_count(tmp, 1);
    if (left_n > right_n) {
        *p = tmp->left;
        while ((*p)->right)
            p = &(*p)->right;
        (*p)->right = tmp->right;
    } else {
        if (tmp->right) {
            *p = tmp->right;
            while ((*p)->left)
                p = &(*p)->left;
            (*p)->left = tmp->left;
        } else
            *p = NULL;
    }
    free(tmp);
}

int node_delete(node **p, int value)
{
    node **loc = node_search(p, value);
    if (*loc) {
        node_remove(loc, value);
        return 1;
    } else
        return 0;
}

void print_tree(node *p)
{
    if (p) {
        print_tree(p->left);
        printf("%d ", p->value);
        print_tree(p->right);
    }
}

int main()
{
    node *p = NULL;
    node_insert(&p, 5);
    node_insert(&p, 3);
    node_insert(&p, 2);
    node_insert(&p, 4);
    node_insert(&p, 1);
    node_insert(&p, 8);
    node_insert(&p, 6);
    node_insert(&p, 7);
    node_insert(&p, 9);
    node_insert(&p, 10);
    print_tree(p);
    printf("\n");
    node_delete(&p, 5);
    print_tree(p);
    printf("\n");
    return 0;
}
