Initializtion
This commit is contained in:
parent
8876568a45
commit
a171e83985
@ -1,32 +1,73 @@
|
||||
#include "binary_search_tree.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
node_t *create_node(int data) {
|
||||
node_t *node = (node_t *)malloc(sizeof(node_t));
|
||||
node->data = data;
|
||||
node->left = NULL;
|
||||
node->right = NULL;
|
||||
return node;
|
||||
}
|
||||
|
||||
node_t *insert_node(node_t *tree, int data) {
|
||||
if (tree == NULL) {
|
||||
return create_node(data);
|
||||
}
|
||||
|
||||
if (data < tree->data) {
|
||||
tree->left = insert_node(tree->left, data);
|
||||
} else if (data > tree->data) {
|
||||
tree->right = insert_node(tree->right, data);
|
||||
}
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
node_t *build_tree(int *tree_data, size_t tree_data_len) {
|
||||
node_t *tree = NULL;
|
||||
for (size_t i = 0; i < tree_data_len; i++) {
|
||||
tree = insert_node(tree, tree_data[i]);
|
||||
if (tree_data_len == 0) {
|
||||
return NULL;
|
||||
}
|
||||
return tree;
|
||||
|
||||
node_t *root = malloc(sizeof(node_t));
|
||||
root->data = tree_data[0];
|
||||
root->left = NULL;
|
||||
root->right = NULL;
|
||||
|
||||
for (size_t i = 1; i < tree_data_len; i++) {
|
||||
node_t *current = root;
|
||||
node_t *parent = NULL;
|
||||
|
||||
while (current!= NULL) {
|
||||
parent = current;
|
||||
if (tree_data[i] < current->data) {
|
||||
current = current->left;
|
||||
} else {
|
||||
current = current->right;
|
||||
}
|
||||
}
|
||||
|
||||
current = malloc(sizeof(node_t));
|
||||
current->data = tree_data[i];
|
||||
current->left = NULL;
|
||||
current->right = NULL;
|
||||
|
||||
if (tree_data[i] < parent->data) {
|
||||
parent->left = current;
|
||||
} else {
|
||||
parent->right = current;
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
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) {
|
||||
int *data = NULL;
|
||||
size_t data_len = 0;
|
||||
|
||||
void in_order_traversal(node_t *node) {
|
||||
if (node == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
in_order_traversal(node->left);
|
||||
|
||||
data = realloc(data, (data_len + 1) * sizeof(int));
|
||||
data[data_len] = node->data;
|
||||
data_len++;
|
||||
|
||||
in_order_traversal(node->right);
|
||||
}
|
||||
|
||||
in_order_traversal(tree);
|
||||
|
||||
return data;
|
||||
}
|
Loading…
Reference in New Issue
Block a user