pvjc24/a3/binary_search_tree.c

79 lines
1.7 KiB
C
Raw Normal View History

2024-04-27 19:26:35 +00:00
#include <stdlib.h>
2024-04-27 19:30:49 +00:00
#include <string.h>
#include <stdio.h>
2024-04-27 19:22:26 +00:00
#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
#include <stddef.h>
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
2024-04-27 19:30:49 +00:00
#include "binary_search_tree.h"
2024-04-27 19:22:26 +00:00
2024-04-27 19:16:17 +00:00
static node_t *create_node(int data) {
2024-04-27 19:30:49 +00:00
node_t *new_node = (node_t *)malloc(sizeof(node_t));
2024-04-27 19:16:17 +00:00
if (new_node != NULL) {
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
}
return new_node;
}
static node_t *insert_node(node_t *root, int data) {
2024-04-27 19:30:49 +00:00
if (root == NULL)
2024-04-27 19:16:17 +00:00
return create_node(data);
2024-04-27 19:30:49 +00:00
if (data <= root->data)
2024-04-27 19:16:17 +00:00
root->left = insert_node(root->left, data);
2024-04-27 19:30:49 +00:00
else
2024-04-27 19:16:17 +00:00
root->right = insert_node(root->right, data);
2024-04-27 19:30:49 +00:00
2024-04-27 19:16:17 +00:00
return root;
}
2024-04-27 19:30:49 +00:00
2024-04-27 19:16:17 +00:00
node_t *build_tree(int *tree_data, size_t tree_data_len) {
node_t *root = NULL;
2024-04-27 19:30:49 +00:00
for (size_t i = 0; i < tree_data_len; ++i)
2024-04-27 19:16:17 +00:00
root = insert_node(root, tree_data[i]);
return root;
}
2024-04-27 19:30:49 +00:00
void free_tree(node_t *tree) {
if (tree == NULL)
return;
free_tree(tree->left);
free_tree(tree->right);
free(tree);
2024-04-27 19:16:17 +00:00
}
2024-04-27 19:30:49 +00:00
static void inorder_traversal(node_t *root, int *result, size_t *index) {
if (root == NULL)
return;
inorder_traversal(root->left, result, index);
result[(*index)++] = root->data;
inorder_traversal(root->right, result, index);
2024-04-27 19:20:50 +00:00
}
2024-04-27 19:18:24 +00:00
2024-04-27 19:16:17 +00:00
int *sorted_data(node_t *tree) {
size_t index = 0;
2024-04-27 19:30:49 +00:00
int *result = (int *)malloc(sizeof(int) * 1000);
if (result != NULL) {
inorder_traversal(tree, result, &index);
2024-04-27 19:16:17 +00:00
}
2024-04-27 19:30:49 +00:00
return result;
2024-04-27 19:18:24 +00:00
}