fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node* Node;
  5. struct Node {
  6. int value;
  7. Node left;
  8. Node right;
  9. };
  10.  
  11. typedef struct Tree* Tree;
  12. struct Tree {
  13. Node root;
  14. };
  15.  
  16. Node Node_new(int value) {
  17. Node s = malloc(sizeof(struct Node));
  18. if (s != NULL) {
  19. s->value = value;
  20. s->left = NULL;
  21. s->right = NULL;
  22. }
  23. return s;
  24. }
  25.  
  26. void Node_add(Node s, Node n) {
  27. if (n->value < s->value) {
  28. if (s->left == NULL) {
  29. s->left = n;
  30. } else {
  31. Node_add(s->left, n);
  32. }
  33. } else {
  34. if (s->right == NULL) {
  35. s->right = n;
  36. } else {
  37. Node_add(s->right, n);
  38. }
  39. }
  40. }
  41.  
  42. void Node_print(Node s) {
  43. if (s->left != NULL) {
  44. Node_print(s->left);
  45. }
  46. printf("%d ", s->value);
  47. if (s->right != NULL) {
  48. Node_print(s->right);
  49. }
  50. }
  51.  
  52. void Node_clean(Node s) {
  53. if (s->left != NULL) {
  54. Node_clean(s->left);
  55. }
  56. if (s->right != NULL) {
  57. Node_clean(s->right);
  58. }
  59. free(s);
  60. }
  61.  
  62. Tree Tree_new(void) {
  63. Tree s = malloc(sizeof(struct Tree));
  64. if (s != NULL) {
  65. s->root = NULL;
  66. }
  67. return s;
  68. }
  69.  
  70. Node Tree_add(Tree s, int value) {
  71. Node n = Node_new(value);
  72. if (n != NULL) {
  73. if (s->root == NULL) {
  74. s->root = n;
  75. } else {
  76. Node_add(s->root, n);
  77. }
  78. }
  79. return n;
  80. }
  81.  
  82. void Tree_print(Tree s) {
  83. if (s->root == NULL) {
  84. printf("empty\n");
  85. } else {
  86. Node_print(s->root);
  87. printf("\n");
  88. }
  89. }
  90.  
  91. void Tree_clean(Tree s) {
  92. if (s->root != NULL) {
  93. Node_clean(s->root);
  94. }
  95. free(s);
  96. }
  97.  
  98. void use_Tree(Tree t, FILE* f) {
  99. char c[10];
  100. while (fgets(c, 10, f) != NULL) {
  101. if (Tree_add(t, atoi(c)) == NULL) {
  102. return;
  103. }
  104. }
  105. Tree_print(t);
  106. }
  107.  
  108. void use_File(FILE* f) {
  109. Tree t = Tree_new();
  110. if (t != NULL) {
  111. use_Tree(t, f);
  112. Tree_clean(t);
  113. }
  114. }
  115.  
  116. int main(void) {
  117. FILE* f;
  118. f = fopen("numbers.txt", "r");
  119. if (f != NULL) {
  120. use_File(f);
  121. fclose(f);
  122. }
  123. return EXIT_SUCCESS;
  124. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty