“program”

This commit is contained in:
Vasylenko 2024-04-23 16:34:12 +02:00
parent fdb05b6f6a
commit ba63d01007

View File

@ -1,65 +1,64 @@
#include "binary_search_tree.h" #include "binary_search_tree.h"
#include <stdlib.h> #include <stdlib.h>
static node_t *insert_node(node_t *root, int value);
static void inorder_traversal(node_t *node, int *array, int *index);
node_t *new_node(int data) { static node_t *new_node(int value) {
node_t *node = malloc(sizeof(node_t)); node_t *node = (node_t *)malloc(sizeof(node_t));
if (node) { if (node == NULL) {
node->data = data; return NULL;
}
node->data = value;
node->left = NULL; node->left = NULL;
node->right = NULL; node->right = NULL;
}
return node; return node;
} }
node_t *insert(node_t *root, int data) {
if (root == NULL) {
return new_node(data);
}
if (data <= root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}
return root;
}
node_t *build_tree(int *tree_data, size_t tree_data_len) { node_t *build_tree(int *tree_data, size_t tree_data_len) {
node_t *root = NULL; node_t *root = NULL;
for (size_t i = 0; i < tree_data_len; i++) { for (size_t i = 0; i < tree_data_len; i++) {
root = insert(root, tree_data[i]); root = insert_node(root, tree_data[i]);
} }
return root; return root;
} }
static node_t *insert_node(node_t *root, int value) {
void free_nodes(node_t *node) { if (root == NULL) {
if (node != NULL) { return new_node(value);
free_nodes(node->left);
free_nodes(node->right);
free(node);
} }
if (value < root->data) {
root->left = insert_node(root->left, value);
} else {
root->right = insert_node(root->right, value);
}
return root;
} }
void free_tree(node_t *tree) { void free_tree(node_t *tree) {
free_nodes(tree); if (tree == NULL) {
} return;
void inorder_traversal(node_t *node, int *array, int *index) {
if (node != NULL) {
inorder_traversal(node->left, array, index);
array[(*index)++] = node->data;
inorder_traversal(node->right, array, index);
} }
free_tree(tree->left);
free_tree(tree->right);
free(tree);
} }
static void inorder_traversal(node_t *node, int *array, int *index) {
if (node == NULL) {
return;
}
inorder_traversal(node->left, array, index);
array[*index] = node->data;
(*index)++;
inorder_traversal(node->right, array, index);
}
int *sorted_data(node_t *tree) { int *sorted_data(node_t *tree) {
int *array = malloc(sizeof(int) * 100); if (tree == NULL) {
return NULL;
}
int *array = (int *)malloc(sizeof(int) * 100);
int index = 0; int index = 0;
inorder_traversal(tree, array, &index); inorder_traversal(tree, array, &index);
return array; return array;