Advertisement
Infernale

Find Structures of Trees [NCTU Floor 7]

Dec 21st, 2019
535
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. int preIndex;
  7.  
  8. class node{
  9.     public:
  10.         char data;
  11.         node* left;
  12.         node* right;
  13. };
  14.  
  15. node* newNode(char data){
  16.     node* Node = new node();
  17.     Node->data = data;
  18.     Node->left = NULL;
  19.     Node->right = NULL;
  20.  
  21.     return (Node);
  22. }
  23.  
  24. int search(string arr, int strt, int end, char value){
  25.     int i;
  26.     for(i = strt; i <= end; i++)
  27.         if(arr[i] == value)
  28.             return i;
  29.     return 0;
  30. }
  31.  
  32. node* buildTree(string in, string pre, int start, int end){
  33.     if(start > end)
  34.         return NULL;
  35.     node* root = newNode(pre[preIndex++]);
  36.     if(start == end)
  37.         return root;
  38.     int i;
  39.     for(i = start; i <= end; i++)
  40.         if(root->data == in[i])
  41.             break;
  42.  
  43.     if(start <= end){
  44.         root->left = buildTree(in, pre, start, i - 1);
  45.  
  46.         root->right = buildTree(in, pre, i + 1, end);
  47.     }
  48.  
  49.     return root;
  50. }
  51.  
  52. void printInorder(node* node, string& ans){
  53.     if(node == NULL)
  54.         return;
  55.     printInorder(node->left, ans);
  56.     printInorder(node->right, ans);
  57.     ans += node->data;
  58. }
  59.  
  60. void deleteTree(node*& node){
  61.     if(node == NULL) return;
  62.     deleteTree(node->left);
  63.     deleteTree(node->right);
  64.     delete node;
  65. }
  66.  
  67. int main(){
  68.     string input;
  69.  
  70.     while(getline(cin, input)){
  71.         preIndex = 0;
  72.         stringstream ss(input);
  73.         string in, pre;
  74.         ss >> pre >> in;
  75.         string ans = "";
  76.         int len = in.size();
  77.         node* root = buildTree(in, pre, 0, len - 1);
  78.         printInorder(root, ans);
  79.         deleteTree(root);
  80.         cout << ans << endl;
  81.     }
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement