2024-04-23 17:33:27 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include "binary_search_tree.h"
|
|
|
|
|
2024-04-23 17:43:45 +00:00
|
|
|
void free_tree(node_t *tree) {
|
|
|
|
if (tree == NULL) {
|
2024-04-23 17:44:34 +00:00
|
|
|
return;
|
2024-04-23 17:43:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
free_tree(tree->left);
|
|
|
|
free_tree(tree->right);
|
|
|
|
|
|
|
|
free(tree);
|
|
|
|
}
|
2024-04-23 17:47:38 +00:00
|
|
|
int *sorted_data(node_t *tree) {
|
2024-04-23 17:49:45 +00:00
|
|
|
if (tree == NULL) {
|
2024-04-23 17:47:38 +00:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t num_nodes = 0;
|
|
|
|
node_t *current = tree;
|
|
|
|
while (current != NULL) {
|
|
|
|
num_nodes++;
|
|
|
|
current = current->right;
|
|
|
|
}
|
|
|
|
|
|
|
|
int *sorted_array = (int *)malloc(num_nodes * sizeof(int));
|
|
|
|
if (sorted_array == NULL) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t index = 0;
|
|
|
|
|
2024-04-23 17:53:07 +00:00
|
|
|
node_t *stack[num_nodes];
|
|
|
|
size_t stack_top = 0;
|
|
|
|
|
|
|
|
while (tree != NULL || stack_top > 0) {
|
|
|
|
while (tree != NULL) {
|
|
|
|
stack[stack_top++] = tree;
|
|
|
|
tree = tree->left;
|
2024-04-23 17:49:45 +00:00
|
|
|
}
|
2024-04-23 17:53:07 +00:00
|
|
|
|
2024-04-23 17:55:17 +00:00
|
|
|
if (stack_top > 0) {
|
|
|
|
tree = stack[--stack_top];
|
|
|
|
sorted_array[index++] = tree->data;
|
|
|
|
tree = tree->right;
|
|
|
|
}
|
2024-04-23 17:49:45 +00:00
|
|
|
}
|
2024-04-23 17:47:38 +00:00
|
|
|
|
|
|
|
return sorted_array;
|
|
|
|
}
|
2024-04-23 17:51:08 +00:00
|
|
|
node_t *build_tree(int *tree_data, size_t tree_data_len) {
|
|
|
|
if (tree_data == NULL || tree_data_len == 0) {
|
|
|
|
return NULL;
|
|
|
|
}
|
2024-04-23 17:33:27 +00:00
|
|
|
|
|
|
|
node_t *koren = (node_t *)malloc(sizeof(node_t));
|
2024-04-23 17:51:08 +00:00
|
|
|
if (koren == NULL) {
|
|
|
|
return NULL;
|
2024-04-23 17:33:27 +00:00
|
|
|
}
|
|
|
|
|
2024-04-23 17:51:08 +00:00
|
|
|
koren->data = tree_data[0];
|
|
|
|
koren->left = NULL;
|
|
|
|
koren->right = NULL;
|
|
|
|
|
|
|
|
if (tree_data_len > 1) {
|
|
|
|
koren->left = build_tree(tree_data + 1, tree_data_len - 1);
|
2024-04-23 17:33:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return koren;
|
|
|
|
}
|
|
|
|
|