fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. struct NODE
  6. {
  7. int val;
  8. struct NODE *left;
  9. struct NODE *right;
  10. };
  11. struct NODE *root = NULL;
  12.  
  13. void insert(int val)
  14. {
  15. struct NODE *new_node;
  16. struct NODE *p;
  17.  
  18. new_node = malloc(sizeof(struct NODE));
  19. new_node->val = val;
  20. new_node->left = new_node->right = NULL;
  21.  
  22. if(root == NULL){
  23. root = new_node;
  24. }
  25. else{
  26. p = root;
  27. while(p != NULL){
  28. if(val < p->val){
  29. if(p->left == NULL){
  30. p->left = new_node;
  31. break;
  32. }
  33. p = p->left;
  34. }
  35. else{
  36. if(p->right == NULL){
  37. p->right = new_node;
  38. break;
  39. }
  40. p = p->right;
  41. }
  42. }
  43. }
  44. }
  45.  
  46. void print(struct NODE *n)
  47. {
  48. if(n == NULL){
  49. return;
  50. }
  51. print(n->left);
  52. printf("%d ", n->val);
  53. print(n->right);
  54. }
  55.  
  56. void insertValues(FILE *f)
  57. {
  58. char c[10];
  59.  
  60. while (fgets(c, 10, f) != NULL) {
  61. insert(atoi(c));
  62. }
  63. }
  64.  
  65. int main(void)
  66. {
  67. FILE *f;
  68.  
  69. f = fopen("numbers.txt", "r");
  70. insertValues(f);
  71. fclose(f);
  72.  
  73. print(root);
  74. printf("\n");
  75. return 0;
  76. }
  77.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty