#include "binary_search_tree.h" #include #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include typedef struct node node_t; struct node { node_t *right; node_t *left; int data; }; node_t *build_tree(int *tree_data, size_t tree_data_len); void free_tree(node_t *tree); int *sorted_data(node_t *tree); #endif static node_t *create_node(int data) { node_t *new_node = malloc(sizeof(node_t)); if (new_node != NULL) { new_node->data = data; new_node->left = NULL; new_node->right = NULL; } return new_node; } static node_t *insert_node(node_t *root, int data) { if (root == NULL) { return create_node(data); } if (data <= root->data) { root->left = insert_node(root->left, data); } else { root->right = insert_node(root->right, data); } return root; } node_t *build_tree(int *tree_data, size_t tree_data_len) { node_t *root = NULL; for (size_t i = 0; i < tree_data_len; i++) { root = insert_node(root, tree_data[i]); } return root; } void free_tree(node_t *tree) { if (tree != NULL) { free_tree(tree->left); free_tree(tree->right); free(tree); } } static void inorder_traversal(node_t *root, int *sorted_array, size_t *index) { if (root != NULL) { inorder_traversal(root->left, sorted_array, index); sorted_array[(*index)++] = root->data; inorder_traversal(root->right, sorted_array, index); } } static size_t count_nodes_helper(node_t *root); size_t count_nodes(node_t *tree) { return count_nodes_helper(tree); } static size_t count_nodes_helper(node_t *root) { if (root == NULL) { return 0; } return 1 + count_nodes_helper(root->left) + count_nodes_helper(root->right); } int *sorted_data(node_t *tree) { size_t index = 0; size_t num_nodes = count_nodes(tree); int *sorted_array = malloc(sizeof(int) * num_nodes); if (sorted_array == NULL) { return NULL; } inorder_traversal(tree, sorted_array, &index); return sorted_array; }