96 lines
2.0 KiB
C
96 lines
2.0 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#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; i<tree_data_len; i++){
|
||
|
add_dereva( first, tree_data[i]);
|
||
|
}
|
||
|
}
|
||
|
void add_dereva(node_t* first, int number){
|
||
|
node_t* buffer=first;
|
||
|
node_t* parent;
|
||
|
|
||
|
while(buffer!=NULL){
|
||
|
parent=buffer;
|
||
|
if(number>buffer->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;
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|