Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1.  
  2. #include "pch.h"
  3. #include <iostream>
  4. #include "string"
  5. #include "algorithm"
  6.  
  7. using namespace std;
  8.  
  9. struct tree
  10. {
  11. int info;
  12. tree *left, *right;
  13. }*root;
  14.  
  15. tree *list(int inf)
  16. {
  17. tree *t = new tree;
  18. t->info = inf;
  19. t->right = t->left = NULL;
  20. return t;
  21. }
  22.  
  23. void add(tree *t)
  24. {
  25. int key, i;
  26. tree *prev;
  27. cin >> key;
  28. bool f = true;
  29. if (t == NULL)
  30. {
  31. root = list(key);
  32. }
  33. else
  34. {
  35. prev = t;
  36. while (t && f)
  37. {
  38. prev = t;
  39. if (key == t->info)
  40. {
  41. f = false;
  42. cout << "kluch use est";
  43. return;
  44. }
  45. else if (key < t->info) t = t->left;
  46. else t = t->right;
  47. }
  48. if (f)
  49. {
  50. t = list(key);
  51. if (key < prev->info) prev->left = t;
  52. else prev->right = t;
  53. }
  54. }
  55. }
  56.  
  57. void view(tree *t, int level)
  58. {
  59. string str;
  60. if (t)
  61. {
  62. view(t->right, level + 1);
  63. for (int i = 0; i < level; i++) str = str + " ";
  64. cout << str << t->info << endl;
  65. view(t->left, level + 1);
  66. }
  67. }
  68.  
  69. void clear(tree *t)
  70. {
  71. if (t != NULL)
  72. {
  73. clear(t->left);
  74. clear(t->right);
  75. delete t;
  76. }
  77. }
  78.  
  79. int count(tree* tr) {
  80. if (tr == NULL)
  81. return 0;
  82. int n = 1;
  83. if (tr->right != NULL)
  84. n += count(tr->right);
  85. return n;
  86. }
  87.  
  88. void main(void)
  89.  
  90. {
  91.  
  92. setlocale(LC_CTYPE, "russian");
  93. int menu, i;
  94. while (true)
  95. {
  96. int n;
  97. cout << "viberite: \n1.dobavit element \n2.prosmotr \n3.poschitac \n4.ydalic \n0.vihod \n";
  98. cin >> menu;
  99. switch (menu)
  100. {
  101. case 1:
  102. cout << "kol elem: ";
  103. cin >> i;
  104. cout << "elementii: ";
  105. while (i-- > 0)
  106. add(root); break;
  107. case 2:
  108. if (root == NULL)
  109. {
  110. cout << "pustoe\n";
  111. break;
  112. }
  113. view(root, 0); cout << endl; break;
  114. case 3:cout << "kol elementov:"; n = count(root->right); cout << n<<"\n\n"; break;
  115. case 4: clear(root); root = NULL; break;
  116. case 0: return;
  117. }
  118. }
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement