This commit is contained in:
Michal Utľák 2024-04-23 19:53:07 +02:00
parent 2a72097c20
commit f644616cc4

View File

@ -30,29 +30,21 @@ int *sorted_data(node_t *tree) {
return NULL; return NULL;
} }
size_t index = 0; size_t index = 0;
node_t *current_node = tree; node_t *stack[num_nodes];
while (current_node != NULL) { size_t stack_top = 0;
if (current_node->left == NULL) {
sorted_array[index++] = current_node->data; while (tree != NULL || stack_top > 0) {
current_node = current_node->right; while (tree != NULL) {
} else { stack[stack_top++] = tree;
node_t *predecessor = current_node->left; tree = tree->left;
while (predecessor->right != NULL && predecessor->right != current_node) {
predecessor = predecessor->right;
} }
if (predecessor->right == NULL) { tree = stack[--stack_top];
predecessor->right = current_node; sorted_array[index++] = tree->data;
current_node = current_node->left;
} else { tree = tree->right;
predecessor->right = NULL;
sorted_array[index++] = current_node->data;
current_node = current_node->right;
}
}
} }
return sorted_array; return sorted_array;