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

typedef struct BinaryTreeNode {
  char* value;
  struct BinaryTreeNode* left;
  struct BinaryTreeNode* right;
} BinaryTreeNode;

typedef struct BinaryTree {
  int node_count;
  struct BinaryTreeNode* root;
} BinaryTree;

BinaryTree* BT_create() { 
  BinaryTree* bt = calloc(sizeof(BinaryTree), 1);
  return bt;
}

void BT_insert_helper(BinaryTreeNode* node, char* val) {
  int r = strcmp(val, node->value);
  if (r < 0) {
    if (node->left != NULL) {
      BT_insert_helper(node->left, val);
    } else {
      BinaryTreeNode* n = calloc(sizeof(BinaryTreeNode), 1);
      n->value = malloc(strlen(val)+1);
      strcpy(n->value, val);
      node->left = n;
      return;
    }
  } else if (r > 0) {
    if (node->right != NULL) {
      BT_insert_helper(node->right, val);
    } else {
      BinaryTreeNode* n = calloc(sizeof(BinaryTreeNode), 1);
      n->value = malloc(strlen(val)+1);
      strcpy(n->value, val);
      node->right = n;
      return;
    }
  } 
}

void BT_insert(BinaryTree* bt, char* val) {
  if (bt->root == NULL) {
    BinaryTreeNode* n = calloc(sizeof(BinaryTreeNode), 1);
    n->value = malloc(strlen(val)+1);
    strcpy(n->value, val);
    bt->root = n;
    return;
  }
  BT_insert_helper(bt->root, val);
}

bool BT_contains_helper(BinaryTreeNode* node, char* val) {
  int r = strcmp(val, node->value);
  if (r < 0) {
    if (node->left != NULL) {
      return BT_contains_helper(node->left, val);
    } else {
      return false;
    }
  } else if (r > 0) {
    if (node->right != NULL) {
      return BT_contains_helper(node->right, val);
    } else {
      return false;
    }
  } else {
    return true;
  }
}

bool BT_contains(BinaryTree* bt, char* val) {
  if (bt->root == NULL) {
    return false;
  }
  return BT_contains_helper(bt->root, val);
}

void BT_print_subtree(BinaryTreeNode* node) {
  if (node == NULL) return;
  printf("[VALUE: %s]\n", node->value);
  BT_print_subtree(node->left);
  BT_print_subtree(node->right);
}

void BT_free_node(BinaryTreeNode* node) {
  if (node == NULL) return;
  BT_free_node(node->left);
  BT_free_node(node->right);
  free(node->value);
  free(node);
}

void BT_free(BinaryTree* bt) {
  BT_free_node(bt->root);
  free(bt);
}

int main() {
  BinaryTree* bt = BT_create();
  BT_insert(bt, "intel");
  BT_insert(bt, "rust");
  BT_insert(bt, "camel");
  BT_insert(bt, "elk");
  BT_print_subtree(bt->root);
  bool c1 = BT_contains(bt, "elk");
  bool c2 = BT_contains(bt, "zach");
  printf("contains: %d\n", c1);
  printf("contains: %d\n", c2);
  BT_free(bt);
  return 0;
}
