2024-04-18 13:16:41 +00:00
|
|
|
#include "binary_search_tree.h"
|
2024-04-18 13:20:29 +00:00
|
|
|
#include <stdlib.h>
|
2024-04-18 13:23:23 +00:00
|
|
|
|
|
|
|
// Deklarace proměnné sorted_index
|
|
|
|
static int sorted_index;
|
|
|
|
|
2024-04-18 13:25:22 +00:00
|
|
|
// Definice funkce insert
|
2024-04-18 13:16:41 +00:00
|
|
|
node_t* insert(node_t *node, int data) {
|
2024-04-18 13:10:03 +00:00
|
|
|
if (node == NULL) {
|
2024-04-18 13:16:41 +00:00
|
|
|
node_t *new_node = (node_t*)malloc(sizeof(node_t));
|
|
|
|
new_node->data = data;
|
|
|
|
new_node->left = NULL;
|
|
|
|
new_node->right = NULL;
|
|
|
|
return new_node;
|
2024-04-18 13:10:03 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
if (data <= node->data) node->left = insert(node->left, data);
|
|
|
|
else node->right = insert(node->right, data);
|
|
|
|
return node;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-18 13:25:22 +00:00
|
|
|
// Definice funkce inorder_traversal
|
2024-04-18 13:20:29 +00:00
|
|
|
void inorder_traversal(node_t *node, int *sorted) {
|
|
|
|
if (node == NULL) return;
|
|
|
|
inorder_traversal(node->left, sorted);
|
|
|
|
sorted[sorted_index++] = node->data;
|
|
|
|
inorder_traversal(node->right, sorted);
|
|
|
|
}
|
|
|
|
|
2024-04-18 13:23:23 +00:00
|
|
|
// Deklarace funkce build_tree
|
2024-04-18 13:16:41 +00:00
|
|
|
node_t* build_tree(int *tree_data, size_t tree_data_len) {
|
|
|
|
node_t *root = NULL;
|
|
|
|
for (size_t i = 0; i < tree_data_len; i++) {
|
|
|
|
root = insert(root, tree_data[i]);
|
|
|
|
}
|
|
|
|
return root;
|
2024-04-18 13:10:03 +00:00
|
|
|
}
|
|
|
|
|
2024-04-18 13:23:23 +00:00
|
|
|
// Deklarace funkce free_tree
|
2024-04-18 13:16:41 +00:00
|
|
|
void free_tree(node_t *tree) {
|
|
|
|
if (tree == NULL) return;
|
|
|
|
free_tree(tree->left);
|
|
|
|
free_tree(tree->right);
|
|
|
|
free(tree);
|
2024-04-18 13:10:03 +00:00
|
|
|
}
|
|
|
|
|
2024-04-18 13:23:23 +00:00
|
|
|
// Deklarace funkce sorted_data
|
2024-04-18 13:16:41 +00:00
|
|
|
int *sorted_data(node_t *tree) {
|
|
|
|
int *sorted = (int*)malloc(sizeof(int) * 1000); // Předpokládáme, že strom má maximálně 1000 prvků
|
|
|
|
sorted_index = 0;
|
|
|
|
inorder_traversal(tree, sorted);
|
|
|
|
return sorted;
|
2024-04-18 13:10:03 +00:00
|
|
|
}
|