2024-04-27 19:16:17 +00:00
|
|
|
#include "binary_search_tree.h"
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
static node_t *create_node(int data) {
|
|
|
|
node_t *new_node = malloc(sizeof(node_t));
|
|
|
|
if (new_node != NULL) {
|
|
|
|
new_node->data = data;
|
|
|
|
new_node->left = NULL;
|
|
|
|
new_node->right = NULL;
|
|
|
|
}
|
|
|
|
return new_node;
|
|
|
|
}
|
|
|
|
|
|
|
|
static node_t *insert_node(node_t *root, int data) {
|
|
|
|
if (root == NULL) {
|
|
|
|
return create_node(data);
|
|
|
|
}
|
|
|
|
if (data <= root->data) {
|
|
|
|
root->left = insert_node(root->left, data);
|
|
|
|
} else {
|
|
|
|
root->right = insert_node(root->right, data);
|
|
|
|
}
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
|
|
|
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_node(root, tree_data[i]);
|
|
|
|
}
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
|
|
|
|
void free_tree(node_t *tree) {
|
|
|
|
if (tree != NULL) {
|
|
|
|
free_tree(tree->left);
|
|
|
|
free_tree(tree->right);
|
|
|
|
free(tree);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void inorder_traversal(node_t *root, int *sorted_array, size_t *index) {
|
|
|
|
if (root != NULL) {
|
|
|
|
inorder_traversal(root->left, sorted_array, index);
|
|
|
|
sorted_array[(*index)++] = root->data;
|
|
|
|
inorder_traversal(root->right, sorted_array, index);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-27 19:18:24 +00:00
|
|
|
static size_t count_nodes_helper(node_t *root) {
|
|
|
|
if (root == NULL) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return 1 + count_nodes_helper(root->left) + count_nodes_helper(root->right);
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t count_nodes(node_t *tree) {
|
|
|
|
return count_nodes_helper(tree);
|
|
|
|
}
|
|
|
|
|
2024-04-27 19:16:17 +00:00
|
|
|
int *sorted_data(node_t *tree) {
|
|
|
|
size_t index = 0;
|
2024-04-27 19:18:24 +00:00
|
|
|
size_t num_nodes = count_nodes(tree);
|
|
|
|
int *sorted_array = malloc(sizeof(int) * num_nodes);
|
2024-04-27 19:16:17 +00:00
|
|
|
if (sorted_array == NULL) {
|
2024-04-27 19:18:24 +00:00
|
|
|
return NULL;
|
2024-04-27 19:16:17 +00:00
|
|
|
}
|
|
|
|
inorder_traversal(tree, sorted_array, &index);
|
|
|
|
return sorted_array;
|
2024-04-27 19:18:24 +00:00
|
|
|
}
|