fork download
  1. #include<iostream>
  2. #include <stdlib.h>
  3.  
  4. using namespace std;
  5.  
  6. struct tree {
  7. char info;
  8. struct tree *left;
  9. struct tree *right;
  10. };
  11.  
  12. struct tree *root; /* начальная вершина дерева */
  13. struct tree *stree(struct tree *root, struct tree *r, char info);
  14. void print_tree(struct tree *root, int l);
  15.  
  16. int main(void)
  17. {
  18. char s[10];
  19.  
  20. root = NULL; /* инициализация корня дерева */
  21. int i = 0;
  22. do {
  23. cout << "Input char: " << endl;
  24. cin >> s;
  25. root = stree(root, root, *s);
  26. i++;
  27. } while (i<10);
  28.  
  29. print_tree(root, 0);
  30.  
  31. return 0;
  32. }
  33.  
  34. struct tree *stree(struct tree *root, struct tree *r, char info)
  35. {
  36.  
  37. if (!r) {
  38. r = (struct tree *) malloc(sizeof(struct tree));
  39. if (!r) {
  40. cout << "Не хватает памяти\n";
  41. exit(0);
  42. }
  43. r->left = NULL;
  44. r->right = NULL;
  45. r->info = info;
  46. if (!root) return r; /* первый вход */
  47. if (info < root->info) root->left = r;
  48. else root->right = r;
  49. return r;
  50. }
  51.  
  52. if (info < r->info)
  53. stree(r, r->left, info);
  54. else
  55. stree(r, r->right, info);
  56.  
  57. return root;
  58. }
  59.  
  60. void print_tree(struct tree *r, int l)
  61. {
  62. int i;
  63.  
  64. if (!r) return;
  65. else //Иначе
  66. {
  67. print_tree(r->left, ++l);//С помощью рекурсивного посещаем левое поддерево
  68. for (int i = 0; i < l; ++i)
  69. cout << "|";
  70. cout<< r->info<<endl; //И показываем элемент
  71. l--;
  72.  
  73. }
  74. print_tree(r->right, ++l); //С помощью рекурсии посещаем правое поддерево
  75.  
  76. }
Success #stdin #stdout 0s 2820KB
stdin
1
2
3
4
5
6
7
8
9
stdout
Input char: 
Input char: 
Input char: 
Input char: 
Input char: 
Input char: 
Input char: 
Input char: 
Input char: 
Input char: 
|1
||2
|||3
||||4
|||||5
||||||6
|||||||7
||||||||8
|||||||||9
||||||||||9