pvjc24/a3/binary_search_tree.c

61 lines
1.5 KiB
C
Raw Normal View History

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
2024-04-18 13:35:37 +00:00
// Deklaracia sorted_index
2024-04-18 13:23:23 +00:00
static int sorted_index;
2024-04-18 13:35:37 +00:00
// Deklaracia funkcie insert
2024-04-18 13:33:36 +00:00
node_t* insert(node_t *node, int data);
2024-04-18 13:35:37 +00:00
// Deklaracia funkcie inorder_traversal
2024-04-18 13:33:36 +00:00
void inorder_traversal(node_t *node, int *sorted);
2024-04-18 13:35:37 +00:00
// Definicia funkcie 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:35:37 +00:00
// Definicia funkcie 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:35:37 +00:00
// Deklaracia funkcie 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:35:37 +00:00
// Deklaracia funkcie 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:35:37 +00:00
// Deklaracia funkcie sorted_data
2024-04-18 13:16:41 +00:00
int *sorted_data(node_t *tree) {
2024-04-18 13:35:37 +00:00
int *sorted = (int*)malloc(sizeof(int) * 1000);
2024-04-18 13:16:41 +00:00
sorted_index = 0;
inorder_traversal(tree, sorted);
return sorted;
2024-04-18 13:10:03 +00:00
}