Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct binary_tree BinaryTree;
- struct binary_tree {
- int value;
- BinaryTree *left;
- BinaryTree *right;
- };
- BinaryTree* create_binary_tree(int value, BinaryTree *left, BinaryTree *right) {
- BinaryTree *binary_tree = malloc(sizeof(BinaryTree));
- binary_tree->value = value;
- binary_tree->left = left;
- binary_tree->right = right;
- return binary_tree;
- }
- BinaryTree* add(BinaryTree *bt, int value) {
- if (bt == NULL) {
- bt = create_binary_tree(value, NULL, NULL);
- } else if (bt->value > value) {
- bt->left = add(bt->left, value);
- } else {
- bt->right = add(bt->right, value);
- }
- return bt;
- }
- void print_binary_tree(BinaryTree *bt) {
- if(bt == NULL) {
- printf(" () ");
- return;
- }
- printf(" ( %d ", bt->value);
- print_binary_tree(bt->left);
- print_binary_tree(bt->right);
- printf(") ");
- }
- void free_binary_tree(BinaryTree *bt) {
- if(bt == NULL) return;
- free_binary_tree(bt->left);
- free_binary_tree(bt->right);
- free(bt);
- }
- int main() {
- int value;
- BinaryTree *bt = NULL;
- while(scanf("%d", &value) != EOF) {
- bt = add(bt, value);
- printf("----\n");
- printf("Adicionando %d\n", value);
- printf(" ");
- print_binary_tree(bt);
- printf("\n");
- }
- printf("----\n");
- free_binary_tree(bt);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement