From 631a979268d32ede54f7a32c3d81b2174d68b9dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tam=C3=A1=C5=A1?= Date: Thu, 18 Apr 2024 12:44:33 +0000 Subject: [PATCH] Update 'a3/binary_search_tree.c' --- a3/binary_search_tree.c | 89 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index e69de29..6d99c67 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -0,0 +1,89 @@ +#include +#include + +typedef struct node { + struct node *right; + struct node *left; + int data; +} node_t; + + +node_t *insert_node(node_t *root, int data); +void free_tree(node_t *tree); +int *sorted_data(node_t *tree, int *count); +void inorder_traversal(node_t *tree, int *arr, int *index); + + +node_t *insert_node(node_t *root, int data) { + if (root == NULL) { + node_t *new_node = malloc(sizeof(node_t)); + if (new_node == NULL) { + return NULL; + } + new_node->data = data; + new_node->left = new_node->right = NULL; + return new_node; + } + if (data <= root->data) { + root->left = insert_node(root->left, data); + } else { + root->right = insert_node(root->right, data); + } + return root; +} + + +void free_tree(node_t *tree) { + if (tree != NULL) { + free_tree(tree->left); + free_tree(tree->right); + free(tree); + } +} + + +void inorder_traversal(node_t *tree, int *arr, int *index) { + if (tree != NULL) { + inorder_traversal(tree->left, arr, index); + arr[*index] = tree->data; + (*index)++; + inorder_traversal(tree->right, arr, index); + } +} + + +int *sorted_data(node_t *tree, int *count) { + *count = 0; + inorder_traversal(tree, NULL, count); + + int *arr = malloc(sizeof(int) * (*count)); + if (arr == NULL) { + return NULL; + } + int index = 0; + inorder_traversal(tree, arr, &index); + return arr; +} + +int main() { + node_t *root = NULL; + int tree_data[] = {4, 2, 6, 1, 3, 5, 7}; + int tree_data_len = sizeof(tree_data) / sizeof(tree_data[0]); + + for (int i = 0; i < tree_data_len; i++) { + root = insert_node(root, tree_data[i]); + } + + int count = 0; + int *sorted = sorted_data(root, &count); + + printf("Sorted data: "); + for (int i = 0; i < count; i++) { + printf("%d ", sorted[i]); + } + printf("\n"); + + free(sorted); + free_tree(root); + return 0; +} \ No newline at end of file