Advertisement
mateuspl

URI: 1191 - Recuperação da Árvore

Feb 4th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  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.     string pre, in;
  54.    
  55.     while (cin >> pre >> in)
  56.     {
  57.         p = pre.begin();
  58.         printTree(find(in));
  59.         cout << endl;
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement