74 lines
1.4 KiB
C
74 lines
1.4 KiB
C
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdio.h>
|
|
#include "binary_search_tree.h"
|
|
|
|
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;
|
|
}
|
|
|
|
size_t num_nodes = 0;
|
|
node_t *current = tree;
|
|
while (current != NULL) {
|
|
num_nodes++;
|
|
current = current->right;
|
|
}
|
|
|
|
int *sorted_array = (int *)malloc(num_nodes * sizeof(int));
|
|
if (sorted_array == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
size_t index = 0;
|
|
|
|
node_t *stack[num_nodes];
|
|
size_t stack_top = 0;
|
|
|
|
while (tree != NULL || stack_top > 0) {
|
|
while (tree != NULL) {
|
|
stack[stack_top++] = tree;
|
|
tree = tree->left;
|
|
}
|
|
|
|
tree = stack[--stack_top];
|
|
sorted_array[index++] = tree->data;
|
|
|
|
tree = tree->right;
|
|
}
|
|
|
|
return sorted_array;
|
|
}
|
|
|
|
node_t *build_tree(int *tree_data, size_t tree_data_len) {
|
|
if (tree_data == NULL || tree_data_len == 0) {
|
|
return NULL;
|
|
}
|
|
|
|
node_t *koren = (node_t *)malloc(sizeof(node_t));
|
|
if (koren == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
koren->data = tree_data[0];
|
|
koren->left = NULL;
|
|
koren->right = NULL;
|
|
|
|
if (tree_data_len > 1) {
|
|
koren->left = build_tree(tree_data + 1, tree_data_len - 1);
|
|
}
|
|
|
|
return koren;
|
|
}
|
|
|