fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6. int a;
  7. Node *l;
  8. Node *r;
  9. };
  10.  
  11. Node *head = NULL,*term = NULL;
  12.  
  13. void Insert(int x, Node *p)
  14. {
  15. if (x>(p->a))
  16. {
  17. if (!p->r)
  18. {
  19. Node *k = new Node;
  20. term = p->r = k;
  21. k->a = x;
  22. k->l=p;
  23. k->r=NULL;
  24. }
  25. else Insert(x,p->r);
  26. }
  27. else
  28. {
  29. if (!p->l)
  30. {
  31. Node *k = new Node;
  32. term = p->l = k;
  33. k->a = x;
  34. k->l=NULL;
  35. k->r=p;
  36. }
  37. else
  38. {
  39. Node *k = new Node;
  40. k->a = x;
  41. k->l=p->l;
  42. k->r=p;
  43. p->l->r=k;
  44. p->l=k;
  45. }
  46.  
  47. }
  48. }
  49.  
  50. void Insert(int x)
  51. {
  52. if (!head)
  53. {
  54. Node *p = new Node;;
  55. head = term = p;
  56. p->a = x;
  57. p->l=NULL;
  58. p->r=NULL;
  59.  
  60. }
  61. else Insert(x,head);
  62. }
  63.  
  64. void Show_1(Node *p)
  65. {
  66. printf("%d ",p->a);
  67. if (p->r) Show_1(p->r);
  68. }
  69. void Show_2(Node *p)
  70. {
  71. printf("%d ",p->a);
  72. if (p->l) Show_2(p->l);
  73. }
  74.  
  75. void Show_1()
  76. {
  77. if (head) Show_1(head);
  78. }
  79. void Show_2()
  80. {
  81. if (term) Show_2(term);
  82. }
  83.  
  84. int main()
  85. {
  86. int x;
  87.  
  88. for (int i=0;i<5;i++) Insert(i);
  89. Show_1();
  90. printf("\n\n");
  91. Show_2();
  92. return 0;
  93. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
0 1 2 3 4 

4 3 2 1 0