mateuspl

URI: 1194 - Prefixa, Infixa e Posfixa

Feb 4th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6.     Node* left = NULL;
  7.     Node* right = NULL;
  8.     char c;
  9. };
  10.  
  11. // Caractere atual na prefixa
  12. string::iterator p;
  13.  
  14. Node* find(string in)
  15. {
  16.     if (in.length())
  17.     {
  18.         string str;
  19.         str.push_back(*p);
  20.  
  21.         size_t i = in.find_first_of(str);
  22.  
  23.         if (i != string::npos)
  24.         {
  25.             Node* node = new Node;
  26.             node->c = *p++;
  27.  
  28.             if (*p != '\0')
  29.             {
  30.                 node->left = find(in.substr(0, i));
  31.                 node->right = find(in.substr(i + 1, in.length() - i));
  32.             }
  33.  
  34.             return node;
  35.         }
  36.     }
  37.  
  38.     return NULL;
  39. }
  40.  
  41. void printTree(Node* node)
  42. {
  43.     if (node == NULL) return;
  44.  
  45.     printTree(node->left);
  46.     printTree(node->right);
  47.  
  48.     cout << node->c;
  49. }
  50.  
  51. int main()
  52. {
  53.     int n;
  54.     cin >> n;
  55.  
  56.     while (n--)
  57.     {
  58.         int len;
  59.         string pre, in;
  60.  
  61.         cin >> len >> pre >> in;
  62.  
  63.         p = pre.begin();
  64.         Node* root = find(in);
  65.  
  66.         printTree(root);
  67.         cout << endl;
  68.     }
  69.  
  70.     return 0;
  71. }
Add Comment
Please, Sign In to add comment