61 lines
1.5 KiB
C
61 lines
1.5 KiB
C
#include "binary_search_tree.h"
|
|
#include <stdlib.h>
|
|
|
|
// Deklaracia sorted_index
|
|
static int sorted_index;
|
|
|
|
// Deklaracia funkcie insert
|
|
node_t* insert(node_t *node, int data);
|
|
|
|
// Deklaracia funkcie inorder_traversal
|
|
void inorder_traversal(node_t *node, int *sorted);
|
|
|
|
// Definicia funkcie insert
|
|
node_t* insert(node_t *node, int data) {
|
|
if (node == NULL) {
|
|
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;
|
|
}
|
|
else {
|
|
if (data <= node->data) node->left = insert(node->left, data);
|
|
else node->right = insert(node->right, data);
|
|
return node;
|
|
}
|
|
}
|
|
|
|
// Definicia funkcie inorder_traversal
|
|
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);
|
|
}
|
|
|
|
// Deklaracia funkcie build_tree
|
|
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;
|
|
}
|
|
|
|
// Deklaracia funkcie free_tree
|
|
void free_tree(node_t *tree) {
|
|
if (tree == NULL) return;
|
|
free_tree(tree->left);
|
|
free_tree(tree->right);
|
|
free(tree);
|
|
}
|
|
|
|
// Deklaracia funkcie sorted_data
|
|
int *sorted_data(node_t *tree) {
|
|
int *sorted = (int*)malloc(sizeof(int) * 1000);
|
|
sorted_index = 0;
|
|
inorder_traversal(tree, sorted);
|
|
return sorted;
|
|
}
|