diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index 2ccc411..4cfa7af 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -14,7 +14,7 @@ void free_tree(node_t *tree) { free(tree); } int *sorted_data(node_t *tree) { - if (tree == NULL) { + if (tree == NULL) { return NULL; } @@ -30,9 +30,30 @@ int *sorted_data(node_t *tree) { return NULL; } + size_t index = 0; - inorder_traversal(tree, sorted_array, &index); + 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; + } + + 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; }