pvjc24/a3/binary_search_tree.c
2024-04-23 20:01:28 +02:00

103 lines
2.5 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include "binary_search_tree.h"
void free_tree(node_t *tree) {
if (tree == NULL) {
return;
}
free_tree(tree->left);
free_tree(tree->right);
free(tree);
}
int *sorted_data(node_t *tree) {
if (tree == NULL) {
return NULL;
}
size_t num_nodes = 0;
node_t *current = tree;
while (current != NULL) {
num_nodes++;
current = current->right;
}
int *sorted_array = (int *)malloc(num_nodes * sizeof(int));
if (sorted_array == NULL) {
return NULL;
}
size_t index = 0;
node_t *current_node = tree;
while (current_node != NULL) {
if (current_node->left == NULL) {
sorted_array[index++] = current_node->data;
current_node = current_node->right;
} else {
node_t *predecessor = current_node->left;
while (predecessor->right != NULL && predecessor->right != current_node) {
predecessor = predecessor->right;
}
if (predecessor->right == NULL) {
predecessor->right = current_node;
current_node = current_node->left;
} else {
predecessor->right = NULL;
sorted_array[index++] = current_node->data;
current_node = current_node->right;
}
}
}
return sorted_array;
}
node_t *build_tree(int *tree_data, size_t tree_data_len) {
if (tree_data == NULL || tree_data_len == 0) {
return NULL;
}
node_t *root = (node_t *)malloc(sizeof(node_t));
if (root == NULL) {
return NULL;
}
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;
}
}
node_t *new_node = (node_t *)malloc(sizeof(node_t));
if (new_node == NULL) {
free_tree(root);
return NULL;
}
new_node->data = tree_data[i];
new_node->left = NULL;
new_node->right = NULL;
if (tree_data[i] < parent->data) {
parent->left = new_node;
} else {
parent->right = new_node;
}
}
return root;
}