76 lines
1.6 KiB
C
76 lines
1.6 KiB
C
#ifndef BINARY_SEARCH_TREE_H
|
|
#define BINARY_SEARCH_TREE_H
|
|
|
|
#include <stddef.h>
|
|
|
|
typedef struct node node_t;
|
|
|
|
struct node {
|
|
node_t *right;
|
|
node_t *left;
|
|
int data;
|
|
};
|
|
|
|
node_t *build_tree(int *tree_data, size_t tree_data_len);
|
|
void free_tree(node_t *tree);
|
|
int *sorted_data(node_t *tree);
|
|
|
|
#endif
|
|
#include "binary_search_tree.h"
|
|
#include <stdlib.h>
|
|
|
|
node_t *new_node(int value) {
|
|
node_t *node = malloc(sizeof(node_t));
|
|
if (node != NULL) {
|
|
node->data = value;
|
|
node->left = NULL;
|
|
node->right = NULL;
|
|
}
|
|
return node;
|
|
}
|
|
|
|
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);
|
|
|
|
return root;
|
|
}
|
|
|
|
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++) {
|
|
root = insert_node(root, tree_data[i]);
|
|
}
|
|
return root;
|
|
}
|
|
|
|
void free_tree(node_t *tree) {
|
|
if (tree != NULL) {
|
|
free_tree(tree->left);
|
|
free_tree(tree->right);
|
|
free(tree);
|
|
}
|
|
}
|
|
|
|
void tree_to_sorted_array(node_t *tree, int arr[], int *index) {
|
|
if (tree != NULL) {
|
|
tree_to_sorted_array(tree->left, arr, index);
|
|
arr[(*index)++] = tree->data;
|
|
tree_to_sorted_array(tree->right, arr, index);
|
|
}
|
|
}
|
|
|
|
int *sorted_data(node_t *tree) {
|
|
if (tree == NULL)
|
|
return NULL;
|
|
|
|
int *arr = malloc(100 * sizeof(int));
|
|
tree_to_sorted_array(tree, arr, &index);
|
|
return arr;
|
|
}
|