From 432e7485ea39744dc0efa7d0d84bebbf5c94ad0c Mon Sep 17 00:00:00 2001 From: kr820js Date: Fri, 26 Apr 2024 12:06:30 +0200 Subject: [PATCH] submit1 --- a3/binary_search_tree.c | 95 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 a3/binary_search_tree.c diff --git a/a3/binary_search_tree.c b/a3/binary_search_tree.c new file mode 100644 index 0000000..2959014 --- /dev/null +++ b/a3/binary_search_tree.c @@ -0,0 +1,95 @@ +#include +#include +#include +#include "binary_search_tree.h" + + +node_t *build_tree(int *tree_data, size_t tree_data_len){ + node_t* first=malloc(sizeof(node_t)); + first->data=tree_data[0]; + first->right=NULL; + first->left=NULL; + + for(int i=1; ibuffer->data){ + buffer=buffer->right; + }else{ + buffer=buffer->left; + } + } + node_t* new_node = malloc(sizeof(node_t)); + new_node->data=number; + new_node->left = NULL; + new_node->right = NULL; + + if(number>parent->data){ + parent->right=new_node; + } else{ + parent->left=new_node; + } +} + +void free_tree(node_t *tree){ + if(tree==NULL){ + return; + } + free_tree(tree->left); + free_tree(tree->right); + free(tree); +} + +int *sorted_data(node_t *tree){ + if(tree==NULL){ + return NULL; + } + int size_of_tree=count_size(tree); + int *result_array=malloc(size_of_tree * sizeof(int)); + int size_of_left=0; + if(tree->left!=NULL){ + size_of_left=count_size(tree->left); + int *left_branch_of_array=sorted_data(tree->left); + memcpy(result_array,left_branch_of_array,size_of_left* sizeof(int)); + free(left_branch_of_array); + } + memcpy(result_array+size_of_left,&tree->data,1* sizeof(int)); + int size_of_right=0; + if(tree->right!=NULL){ + size_of_right=count_size(tree->right); + int *right_branch_of_array=sorted_data(tree->right); + memcpy(result_array+size_of_left+1,right_branch_of_array,size_of_right * sizeof(int)); + free(right_branch_of_array); + } + + return result_array; +} + +int count_size(node_t *tree){ + if(tree==NULL){ + return 0; + } + int left=count_size(tree->left); + int right=count_size(tree->right); + int counter=left+right+1; + + return counter; +} + + + + + + + + + + +