fork download
  1. #include <stdlib.h>
  2. #include<stdio.h>
  3.  
  4.  
  5.  
  6.  
  7. struct node
  8. {
  9. int number;
  10. struct node *left;
  11. struct node *right;
  12. };
  13.  
  14. void add(struct node *top, int newNodeNumber)
  15. {
  16. if (top->number == 0)
  17. {
  18. top->number = newNodeNumber;
  19. }
  20. else if (top->number> newNodeNumber)
  21. {
  22. if (top->left == NULL)
  23. {
  24. struct node *newNode = (struct node *)malloc(sizeof(struct node));
  25. newNode->number = newNodeNumber;
  26.  
  27. top->left = newNode;
  28. }
  29. else
  30. {
  31. add(top->left, newNodeNumber);
  32. }
  33. }
  34. else
  35. {
  36. if (top->right == NULL)
  37. {
  38. struct node *newNode = (struct node *)malloc(sizeof(struct node));
  39. newNode->number = newNodeNumber;
  40. top->right = newNode;
  41. }
  42. else
  43. {
  44. add(top->right, newNodeNumber);
  45. }
  46.  
  47. }
  48. }
  49.  
  50. void printNode(struct node *top)
  51. {
  52. if (top->left != NULL)
  53. {
  54. printNode(top->left);
  55. }
  56.  
  57. int n = top->number;
  58. printf("%d\n", n);
  59.  
  60. if (top->right != NULL)
  61. {
  62. printNode(top->right);
  63. }
  64.  
  65. }
  66.  
  67.  
  68. int main()
  69. {
  70. struct node
  71. {
  72. int number;
  73. struct node *left;
  74. struct node *right;
  75. };
  76. struct node *top = (struct node *)malloc(sizeof(struct node));
  77. top->number = 0;
  78. top->left = NULL;
  79. top->right = NULL;
  80.  
  81. add(top, 4);
  82. add(top, 5);
  83. add(top, 2);
  84. printNode(top);
  85. return 0;
  86. }
  87.  
Success #stdin #stdout 0.01s 9424KB
stdin
Standard input is empty
stdout
2
4
5