This commit is contained in:
Michal Utľák 2024-04-23 20:01:28 +02:00
parent e40b7d33ad
commit ae4781d33f

View File

@ -1,5 +1,4 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
#include <stdio.h> #include <stdio.h>
#include "binary_search_tree.h" #include "binary_search_tree.h"
@ -13,6 +12,7 @@ void free_tree(node_t *tree) {
free(tree); free(tree);
} }
int *sorted_data(node_t *tree) { int *sorted_data(node_t *tree) {
if (tree == NULL) { if (tree == NULL) {
return NULL; return NULL;
@ -32,42 +32,72 @@ int *sorted_data(node_t *tree) {
size_t index = 0; size_t index = 0;
node_t *stack[num_nodes]; node_t *current_node = tree;
size_t stack_top = 0; while (current_node != NULL) {
if (current_node->left == NULL) {
while (tree != NULL || stack_top > 0) { sorted_array[index++] = current_node->data;
while (tree != NULL) { current_node = current_node->right;
stack[stack_top++] = tree; } else {
tree = tree->left; node_t *predecessor = current_node->left;
while (predecessor->right != NULL && predecessor->right != current_node) {
predecessor = predecessor->right;
} }
if (stack_top > 0) { if (predecessor->right == NULL) {
tree = stack[--stack_top]; predecessor->right = current_node;
sorted_array[index++] = tree->data; current_node = current_node->left;
tree = tree->right; } else {
predecessor->right = NULL;
sorted_array[index++] = current_node->data;
current_node = current_node->right;
}
} }
} }
return sorted_array; return sorted_array;
} }
node_t *build_tree(int *tree_data, size_t tree_data_len) { node_t *build_tree(int *tree_data, size_t tree_data_len) {
if (tree_data == NULL || tree_data_len == 0) { if (tree_data == NULL || tree_data_len == 0) {
return NULL; return NULL;
} }
node_t *koren = (node_t *)malloc(sizeof(node_t)); node_t *root = (node_t *)malloc(sizeof(node_t));
if (koren == NULL) { if (root == NULL) {
return NULL; return NULL;
} }
koren->data = tree_data[0]; root->data = tree_data[0];
koren->left = NULL; root->left = NULL;
koren->right = NULL; root->right = NULL;
if (tree_data_len > 1) { for (size_t i = 1; i < tree_data_len; i++) {
koren->left = build_tree(tree_data + 1, tree_data_len - 1); 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;
}
} }
return koren; 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 root;
}