title
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
solution
/**
* 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* f(vector<int>& post,vector<int> mid,int a,int b,int c,int d){
if(a>b||c>d)
return NULL;
int v=post[b];
int m=c;
for(int i=c;i<=d;i++){
if(mid[i]==v){
m=i;
break;
}
}
TreeNode *root=new TreeNode(post[b]);
root->left=f(post,mid,a,a+m-c-1,c,m-1);
root->right=f(post,mid,a+m-c,b-1,m+1,d);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode* root=f(postorder,inorder,0,postorder.size()-1,0,inorder.size()-1);
return root;
}
};