diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c new file mode 100644 index 0000000..4c65468 --- /dev/null +++ b/a3/binary_search_tree.c @@ -0,0 +1,67 @@ +#include "binary_search_tree.h" +#include + + +node_t *new_node(int data) { + node_t *node = malloc(sizeof(node_t)); + if (node) { + node->data = data; + node->left = NULL; + node->right = NULL; + } + return node; +} + + +node_t *insert(node_t *root, int data) { + if (root == NULL) { + return new_node(data); + } + if (data <= root->data) { + root->left = insert(root->left, data); + } else { + root->right = insert(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(root, tree_data[i]); + } + return root; +} + + +void free_nodes(node_t *node) { + if (node != NULL) { + free_nodes(node->left); + free_nodes(node->right); + free(node); + } +} + + +void free_tree(node_t *tree) { + free_nodes(tree); +} + + +void inorder_traversal(node_t *node, int *array, int *index) { + if (node != NULL) { + inorder_traversal(node->left, array, index); + array[(*index)++] = node->data; + inorder_traversal(node->right, array, index); + } +} + + +int *sorted_data(node_t *tree) { + int *array = malloc(sizeof(int) * 100); + int index = 0; + inorder_traversal(tree, array, &index); + return array; +} +