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;
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) { while (tree != NULL || stack_top > 0) {
predecessor->right = current_node; while (tree != NULL) {
current_node = current_node->left; stack[stack_top++] = tree;
} else { tree = tree->left;
predecessor->right = NULL;
sorted_array[index++] = current_node->data;
current_node = current_node->right;
}
} }
tree = stack[--stack_top];
sorted_array[index++] = tree->data;
tree = tree->right;
} }
return sorted_array; return sorted_array;