Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. using namespace std;
  6. typedef char type;
  7.  
  8. struct elem{
  9. elem* l = nullptr;
  10. elem* r = nullptr;
  11. type atom;
  12. };
  13.  
  14.  
  15. void make_space(string& str){
  16. for (int i = 0; i < str.size(); i++){
  17. if (str[i + 1] != ' ' && str[i] != ' ') {
  18. str.insert(i + 1, " ");
  19. i++;
  20. }
  21. }
  22. }
  23.  
  24.  
  25. elem* create_left(elem* bin_tree, type atom){
  26. elem* push = new elem;
  27.  
  28. bin_tree->l = push;
  29. bin_tree = bin_tree->l;
  30. bin_tree->atom = atom;
  31.  
  32. return bin_tree;
  33. }
  34.  
  35.  
  36. elem* create_right(elem* bin_tree, type atom){
  37. elem* push = new elem;
  38.  
  39. bin_tree->r = push;
  40. bin_tree = bin_tree->r;
  41. bin_tree->atom = atom;
  42.  
  43. return bin_tree;
  44. }
  45.  
  46. //(a (b (d #(h # #))(e # #))(c (f (i # #)(j # #))(g #(k (l # #) #))))
  47. elem* create_bin_tree(elem* tree, istringstream& stream, bool init) {
  48.  
  49. if (init){
  50. tree = new elem;
  51. }
  52.  
  53.  
  54. char x;
  55. elem* cur = tree;
  56. stream >> x;
  57.  
  58. if (x == '('){
  59.  
  60. stream >> x;
  61. if (init){
  62. tree->atom = x;
  63. init = false;
  64. create_bin_tree(tree, stream, init);
  65. }else {
  66. tree = create_left(cur, x);
  67. create_bin_tree(tree, stream, init);
  68. }
  69. }
  70. if (x == '#'){
  71. stream >> x;
  72. if (x == '('){
  73. stream >> x;
  74. tree = create_right(cur, x);
  75. create_bin_tree(tree, stream, init);
  76. }
  77. }
  78. stream >> x;
  79. if (x == ')'){
  80. return nullptr;
  81. }
  82. if (x == '('){
  83. stream >> x;
  84. tree = create_right(cur, x);
  85. create_bin_tree(tree, stream, init);
  86. }
  87. stream >> x;
  88. return cur;
  89. }
  90.  
  91.  
  92. int main(){
  93. string str_bin_tree1;
  94. char x;
  95. elem* bin_tree1 = nullptr;
  96.  
  97. getline(cin, str_bin_tree1);
  98.  
  99. make_space(str_bin_tree1);
  100. istringstream stream1(str_bin_tree1);
  101.  
  102. bin_tree1 = create_bin_tree(nullptr, stream1, true);
  103.  
  104. return 0;
  105. }
  106.  
  107. //(a (b (d #(h # #))(e # #))(c (f (i # #)(j # #))(g #(k (l # #) #))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement