diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index 033d628..737b806 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -1,5 +1,4 @@ #include -#include #include #include "binary_search_tree.h" @@ -13,6 +12,7 @@ void free_tree(node_t *tree) { free(tree); } + int *sorted_data(node_t *tree) { if (tree == NULL) { return NULL; @@ -32,42 +32,72 @@ int *sorted_data(node_t *tree) { size_t index = 0; - node_t *stack[num_nodes]; - size_t stack_top = 0; + node_t *current_node = tree; + while (current_node != NULL) { + if (current_node->left == NULL) { + sorted_array[index++] = current_node->data; + current_node = current_node->right; + } else { + node_t *predecessor = current_node->left; + while (predecessor->right != NULL && predecessor->right != current_node) { + predecessor = predecessor->right; + } - while (tree != NULL || stack_top > 0) { - while (tree != NULL) { - stack[stack_top++] = tree; - tree = tree->left; - } - - if (stack_top > 0) { - tree = stack[--stack_top]; - sorted_array[index++] = tree->data; - tree = tree->right; + if (predecessor->right == NULL) { + predecessor->right = current_node; + current_node = current_node->left; + } else { + predecessor->right = NULL; + sorted_array[index++] = current_node->data; + current_node = current_node->right; + } } } return sorted_array; } + node_t *build_tree(int *tree_data, size_t tree_data_len) { if (tree_data == NULL || tree_data_len == 0) { return NULL; } - node_t *koren = (node_t *)malloc(sizeof(node_t)); - if (koren == NULL) { + node_t *root = (node_t *)malloc(sizeof(node_t)); + if (root == NULL) { return NULL; } - koren->data = tree_data[0]; - koren->left = NULL; - koren->right = NULL; + root->data = tree_data[0]; + root->left = NULL; + root->right = NULL; - if (tree_data_len > 1) { - koren->left = build_tree(tree_data + 1, tree_data_len - 1); + for (size_t i = 1; i < tree_data_len; i++) { + node_t *current = root; + node_t *parent = NULL; + while (current != NULL) { + parent = current; + if (tree_data[i] < current->data) { + current = current->left; + } else { + current = current->right; + } + } + + node_t *new_node = (node_t *)malloc(sizeof(node_t)); + if (new_node == NULL) { + free_tree(root); + return NULL; + } + new_node->data = tree_data[i]; + new_node->left = NULL; + new_node->right = NULL; + + if (tree_data[i] < parent->data) { + parent->left = new_node; + } else { + parent->right = new_node; + } } - return koren; -} - + return root; +} \ No newline at end of file