diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index e69de29..4294728 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -0,0 +1,63 @@ +#include "binary_search_tree.h" +#include +#include +#include + +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); + } +} + +int *sorted_data(node_t *tree) { + size_t index = 0; + int *sorted_array = malloc(sizeof(int) * count_nodes(tree)); + if (sorted_array == NULL) { + return NULL; + } + inorder_traversal(tree, sorted_array, &index); + return sorted_array; +}