diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index 6463b19..d8e33d3 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -1,6 +1,6 @@ - -#include "binary_search_tree.h" #include +#include +#include #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include @@ -18,9 +18,11 @@ void free_tree(node_t *tree); int *sorted_data(node_t *tree); #endif +#include "binary_search_tree.h" + static node_t *create_node(int data) { - node_t *new_node = malloc(sizeof(node_t)); + node_t *new_node = (node_t *)malloc(sizeof(node_t)); if (new_node != NULL) { new_node->data = data; new_node->left = NULL; @@ -30,61 +32,48 @@ static node_t *create_node(int data) { } static node_t *insert_node(node_t *root, int data) { - if (root == NULL) { + if (root == NULL) return create_node(data); - } - if (data <= root->data) { + + if (data <= root->data) root->left = insert_node(root->left, data); - } else { + 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++) { + 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); - } + if (tree == NULL) + return; + 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 void inorder_traversal(node_t *root, int *result, size_t *index) { + if (root == NULL) + return; + inorder_traversal(root->left, result, index); + result[(*index)++] = root->data; + inorder_traversal(root->right, result, 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; + int *result = (int *)malloc(sizeof(int) * 1000); + if (result != NULL) { + inorder_traversal(tree, result, &index); } - inorder_traversal(tree, sorted_array, &index); - return sorted_array; + return result; } \ No newline at end of file