pvjc24/a3/binary_search_tree.c

67 lines
1.5 KiB
C
Raw Normal View History

2024-04-23 13:12:37 +00:00
#include "binary_search_tree.h"
#include <stdlib.h>
2024-04-23 14:34:12 +00:00
static node_t *insert_node(node_t *root, int value);
static void inorder_traversal(node_t *node, int *array, int *index);
2024-04-23 13:12:37 +00:00
2024-04-23 14:34:12 +00:00
static node_t *new_node(int value) {
node_t *node = (node_t *)malloc(sizeof(node_t));
if (node == NULL) {
return NULL;
2024-04-23 13:12:37 +00:00
}
2024-04-23 14:34:12 +00:00
node->data = value;
node->left = NULL;
node->right = NULL;
2024-04-23 13:12:37 +00:00
return node;
}
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++) {
2024-04-23 14:34:12 +00:00
root = insert_node(root, tree_data[i]);
2024-04-23 13:12:37 +00:00
}
return root;
}
2024-04-23 14:34:12 +00:00
static node_t *insert_node(node_t *root, int value) {
if (root == NULL) {
return new_node(value);
}
if (value < root->data) {
root->left = insert_node(root->left, value);
} else {
root->right = insert_node(root->right, value);
2024-04-23 13:12:37 +00:00
}
2024-04-23 14:34:12 +00:00
return root;
2024-04-23 13:12:37 +00:00
}
void free_tree(node_t *tree) {
2024-04-23 14:34:12 +00:00
if (tree == NULL) {
return;
}
free_tree(tree->left);
free_tree(tree->right);
free(tree);
2024-04-23 13:12:37 +00:00
}
2024-04-23 14:34:12 +00:00
static void inorder_traversal(node_t *node, int *array, int *index) {
if (node == NULL) {
return;
2024-04-23 13:12:37 +00:00
}
2024-04-23 14:34:12 +00:00
inorder_traversal(node->left, array, index);
array[*index] = node->data;
(*index)++;
inorder_traversal(node->right, array, index);
2024-04-23 13:12:37 +00:00
}
int *sorted_data(node_t *tree) {
2024-04-23 14:34:12 +00:00
if (tree == NULL) {
return NULL;
}
int *array = (int *)malloc(sizeof(int) * 100);
2024-04-23 13:12:37 +00:00
int index = 0;
inorder_traversal(tree, array, &index);
return array;
}