pvjc24/a3/binary_search_tree.c

84 lines
1.8 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:31:24 +00:00
#include <string.h>
2024-04-25 19:19:47 +00:00
2024-04-25 19:33:23 +00:00
int count_nodes(node_t *tree);
void in_order_traversal(node_t *tree, int **ptr);
2024-04-25 19:29:28 +00:00
node_t *build_tree(int *tree_data, size_t tree_data_len) {
if (tree_data_len == 0) {
return NULL;
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:29:28 +00:00
node_t *root = malloc(sizeof(node_t));
root->data = tree_data[0];
root->left = NULL;
root->right = NULL;
for (size_t i = 1; i < tree_data_len; i++) {
node_t *current = root;
node_t *parent = NULL;
while (current!= NULL) {
parent = current;
if (tree_data[i] < current->data) {
current = current->left;
} else {
current = current->right;
2024-04-25 19:36:52 +00:00
}
2024-04-25 19:29:28 +00:00
}
current = malloc(sizeof(node_t));
2024-04-25 19:36:52 +00:00
if (current == NULL) {
free_tree(root);
return NULL;
}
2024-04-25 19:29:28 +00:00
current->data = tree_data[i];
current->left = NULL;
current->right = NULL;
if (tree_data[i] < parent->data) {
parent->left = current;
} else {
parent->right = current;
}
2024-04-25 19:22:23 +00:00
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:29:28 +00:00
return root;
}
void free_tree(node_t *tree) {
if (tree == NULL) {
return;
2024-04-25 19:22:23 +00:00
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:29:28 +00:00
free_tree(tree->left);
free_tree(tree->right);
free(tree);
2024-04-25 19:22:23 +00:00
}
2024-04-25 19:19:47 +00:00
2024-04-25 19:29:28 +00:00
int *sorted_data(node_t *tree) {
2024-04-25 19:31:24 +00:00
int *data = malloc(sizeof(int) * count_nodes(tree));
int *ptr = data;
in_order_traversal(tree, &ptr);
2024-04-25 19:29:28 +00:00
return data;
2024-04-25 19:31:24 +00:00
}
2024-04-25 19:33:23 +00:00
int count_nodes(node_t *tree) {
if (tree == NULL) {
return 0;
}
return 1 + count_nodes(tree->left) + count_nodes(tree->right);
}
void in_order_traversal(node_t *tree, int **ptr) {
if (tree == NULL) {
return;
}
in_order_traversal(tree->left, ptr);
**ptr = tree->data;
(*ptr)++;
in_order_traversal(tree->right, ptr);
}