Update 'a3/binary_search_tree.c'
This commit is contained in:
parent
81742cafdf
commit
631a979268
@ -0,0 +1,89 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct node {
|
||||
struct node *right;
|
||||
struct node *left;
|
||||
int data;
|
||||
} node_t;
|
||||
|
||||
|
||||
node_t *insert_node(node_t *root, int data);
|
||||
void free_tree(node_t *tree);
|
||||
int *sorted_data(node_t *tree, int *count);
|
||||
void inorder_traversal(node_t *tree, int *arr, int *index);
|
||||
|
||||
|
||||
node_t *insert_node(node_t *root, int data) {
|
||||
if (root == NULL) {
|
||||
node_t *new_node = malloc(sizeof(node_t));
|
||||
if (new_node == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
new_node->data = data;
|
||||
new_node->left = new_node->right = NULL;
|
||||
return new_node;
|
||||
}
|
||||
if (data <= root->data) {
|
||||
root->left = insert_node(root->left, data);
|
||||
} else {
|
||||
root->right = insert_node(root->right, data);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
|
||||
void free_tree(node_t *tree) {
|
||||
if (tree != NULL) {
|
||||
free_tree(tree->left);
|
||||
free_tree(tree->right);
|
||||
free(tree);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void inorder_traversal(node_t *tree, int *arr, int *index) {
|
||||
if (tree != NULL) {
|
||||
inorder_traversal(tree->left, arr, index);
|
||||
arr[*index] = tree->data;
|
||||
(*index)++;
|
||||
inorder_traversal(tree->right, arr, index);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int *sorted_data(node_t *tree, int *count) {
|
||||
*count = 0;
|
||||
inorder_traversal(tree, NULL, count);
|
||||
|
||||
int *arr = malloc(sizeof(int) * (*count));
|
||||
if (arr == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
int index = 0;
|
||||
inorder_traversal(tree, arr, &index);
|
||||
return arr;
|
||||
}
|
||||
|
||||
int main() {
|
||||
node_t *root = NULL;
|
||||
int tree_data[] = {4, 2, 6, 1, 3, 5, 7};
|
||||
int tree_data_len = sizeof(tree_data) / sizeof(tree_data[0]);
|
||||
|
||||
for (int i = 0; i < tree_data_len; i++) {
|
||||
root = insert_node(root, tree_data[i]);
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
int *sorted = sorted_data(root, &count);
|
||||
|
||||
printf("Sorted data: ");
|
||||
for (int i = 0; i < count; i++) {
|
||||
printf("%d ", sorted[i]);
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
free(sorted);
|
||||
free_tree(root);
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user