From 6672cd141ac04b5d01f9624644418521dbd5a67b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tam=C3=A1=C5=A1?= Date: Thu, 18 Apr 2024 12:50:53 +0000 Subject: [PATCH] Update 'a3/binary_search_tree.c' --- a3/binary_search_tree.c | 75 ----------------------------------------- 1 file changed, 75 deletions(-) diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c index 4f50c59..e69de29 100644 --- a/a3/binary_search_tree.c +++ b/a3/binary_search_tree.c @@ -1,75 +0,0 @@ -#ifndef BINARY_SEARCH_TREE_H -#define BINARY_SEARCH_TREE_H - -#include - -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 - -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; -}