pvjc24/a3/binary_search_tree.c

59 lines
1.4 KiB
C
Raw Normal View History

2024-04-25 19:19:47 +00:00
#include "binary_search_tree.h"
#include <stdlib.h>
2024-04-25 19:22:23 +00:00
node_t *create_node(int data) {
node_t *node = (node_t *)malloc(sizeof(node_t));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:22:23 +00:00
node_t *insert_node(node_t *tree, int data) {
if (tree == NULL) {
return create_node(data);
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:22:23 +00:00
if (data < tree->data) {
tree->left = insert_node(tree->left, data);
} else if (data > tree->data) {
tree->right = insert_node(tree->right, data);
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:22:23 +00:00
return tree;
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:22:23 +00:00
node_t *build_tree(int *tree_data, size_t tree_data_len) {
node_t *tree = NULL;
for (size_t i = 0; i < tree_data_len; i++) {
tree = insert_node(tree, tree_data[i]);
2024-04-25 19:19:47 +00:00
}
2024-04-25 19:22:23 +00:00
return tree;
2024-04-25 19:19:47 +00:00
}
void free_tree(node_t *tree) {
if (tree == NULL) {
return;
}
free_tree(tree->left);
free_tree(tree->right);
free(tree);
}
2024-04-25 19:22:23 +00:00
void in_order_traversal(node_t *tree, int *sorted_data, int *index) {
if (tree == NULL) {
return;
2024-04-25 19:19:47 +00:00
}
2024-04-25 19:22:23 +00:00
in_order_traversal(tree->left, sorted_data, index);
sorted_data[(*index)++] = tree->data;
in_order_traversal(tree->right, sorted_data, index);
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:22:23 +00:00
int *sorted_data(node_t *tree, size_t tree_data_len) {
int *sorted_data = (int *)malloc(tree_data_len * sizeof(int));
int index = 0;
in_order_traversal(tree, sorted_data, &index);
return sorted_data;
2024-04-25 19:19:47 +00:00
}