diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index 4294728..69d4a11 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -1,7 +1,5 @@ #include "binary_search_tree.h" #include -#include -#include static node_t *create_node(int data) { node_t *new_node = malloc(sizeof(node_t)); @@ -25,7 +23,6 @@ static node_t *insert_node(node_t *root, int 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++) { @@ -34,7 +31,6 @@ node_t *build_tree(int *tree_data, size_t tree_data_len) { return root; } - void free_tree(node_t *tree) { if (tree != NULL) { free_tree(tree->left); @@ -43,7 +39,6 @@ void free_tree(node_t *tree) { } } - static void inorder_traversal(node_t *root, int *sorted_array, size_t *index) { if (root != NULL) { inorder_traversal(root->left, sorted_array, index); @@ -52,12 +47,24 @@ static void inorder_traversal(node_t *root, int *sorted_array, size_t *index) { } } +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); +} + +size_t count_nodes(node_t *tree) { + return count_nodes_helper(tree); +} + int *sorted_data(node_t *tree) { size_t index = 0; - int *sorted_array = malloc(sizeof(int) * count_nodes(tree)); + size_t num_nodes = count_nodes(tree); + int *sorted_array = malloc(sizeof(int) * num_nodes); if (sorted_array == NULL) { - return NULL; + return NULL; } inorder_traversal(tree, sorted_array, &index); return sorted_array; -} +} \ No newline at end of file