Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre
and post
are distinct positive integers.
Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Note:
1 <= pre.length == post.length <= 30
pre[]
andpost[]
are both permutations of1, 2, ..., pre.length
.- It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
/**
* 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* tree(vector<int>& pre, vector<int>& post,int pa,int pb,int ia,int ib){
if(pb<pa)
return NULL;
TreeNode *t=new TreeNode(pre[pa]);
if(pb==pa)
return t;
int k;
for(k=ia;k<ib;++k)
if(post[k]==pre[pa+1])
break;
t->left=tree(pre,post,pa+1,pa+k-ia+1,ia,k);
t->right=tree(pre,post,pa+k-ia+2,pb,k+1,ib-1);
return t;
}
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
int n=pre.size();
if(n==0)
return NULL;
TreeNode *t=tree(pre,post,0,n-1,0,n-1);
return t;
}
};