#include <iostream>
#include <stack>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(vin.empty()){
return nullptr;
}
TreeNode *root = new TreeNode(pre[0]);
vector <int> left_pre, right_pre, left_vin, right_vin;
int len = 0;
for (int i = 0; i < vin.size(); i++){
if(vin[i] == pre[0]){
len = i;
break;
}
}
for(int i = 0; i < len; i++){
left_pre.push_back(pre[i+1]);
left_vin.push_back(vin[i]);
}
for(int i = len+1; i < vin.size(); i++){
right_pre.push_back(pre[i]);
right_vin.push_back(vin[i]);
}
root->left = reConstructBinaryTree(left_pre, left_vin);
root->right = reConstructBinaryTree(right_pre, right_vin);
return root;
}
void postorder(TreeNode *root){
if(root != nullptr){
postorder(root->left);
postorder(root->right);
cout << root->val <<endl;
}
}
};
int main()
{
Solution s;
vector <int> pre {1,2,4,7,3,5,6,8};
vector <int> vin {4,7,2,1,5,3,8,6};
TreeNode * res = s.reConstructBinaryTree(pre, vin);
s.postorder(res);
return 0;
}