/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
return helper(pre, 0, pre.size()-1, post, 0, post.size()-1);
}
TreeNode* helper(vector<int>& pre, int s1, int e1, vector<int>& post, int s2, int e2){
if(s1>e1 || s2>e2) return NULL;
TreeNode* cur = new TreeNode(pre[s1]);
int cnt=0;
for(int i=s2;i<e2;i++){
cnt++;
if(post[i]==pre[s1+1] && post[e2-1]==pre[s1-s2+i+2]) break;
}
cur->left = helper(pre, s1+1, s1+cnt, post, s2, s2+cnt-1);
cur->right = helper(pre, s1+1+cnt, e1, post, s2+cnt, e2-1);
return cur;
}
};