Advertisement
Guest User

783 - Inserção em Árvores de Busca Binária

a guest
Oct 26th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct binary_tree BinaryTree;
  5. struct binary_tree {
  6. int value;
  7. BinaryTree *left;
  8. BinaryTree *right;
  9. };
  10.  
  11. BinaryTree* create_binary_tree(int value, BinaryTree *left, BinaryTree *right) {
  12. BinaryTree *binary_tree = malloc(sizeof(BinaryTree));
  13.  
  14. binary_tree->value = value;
  15. binary_tree->left = left;
  16. binary_tree->right = right;
  17.  
  18. return binary_tree;
  19. }
  20.  
  21. BinaryTree* add(BinaryTree *bt, int value) {
  22. if (bt == NULL) {
  23. bt = create_binary_tree(value, NULL, NULL);
  24. } else if (bt->value > value) {
  25. bt->left = add(bt->left, value);
  26. } else {
  27. bt->right = add(bt->right, value);
  28. }
  29.  
  30. return bt;
  31. }
  32.  
  33. void print_binary_tree(BinaryTree *bt) {
  34. if(bt == NULL) {
  35. printf(" () ");
  36. return;
  37. }
  38.  
  39. printf(" ( %d ", bt->value);
  40.  
  41. print_binary_tree(bt->left);
  42. print_binary_tree(bt->right);
  43. printf(") ");
  44. }
  45.  
  46. void free_binary_tree(BinaryTree *bt) {
  47. if(bt == NULL) return;
  48.  
  49. free_binary_tree(bt->left);
  50. free_binary_tree(bt->right);
  51.  
  52. free(bt);
  53. }
  54.  
  55. int main() {
  56. int value;
  57. BinaryTree *bt = NULL;
  58.  
  59. while(scanf("%d", &value) != EOF) {
  60. bt = add(bt, value);
  61.  
  62. printf("----\n");
  63. printf("Adicionando %d\n", value);
  64. printf(" ");
  65. print_binary_tree(bt);
  66. printf("\n");
  67. }
  68.  
  69. printf("----\n");
  70.  
  71. free_binary_tree(bt);
  72.  
  73. return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement