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
/**
* 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>& postorder, vector<int>& inorder,int pa,int pb,int ia,int ib){//cout<<"here"<<endl;
if(pb<pa)
return NULL;
TreeNode *t=new TreeNode(postorder[pb]);
if(pb==pa)
return t;
int k;
for(k=ia;k<=ib;++k)
if(inorder[k]==postorder[pb])
break;
t->left=tree(postorder,inorder,pa,pa+k-ia-1,ia,k-1);
t->right=tree(postorder,inorder,pa+k-ia,pb-1,k+1,ib);
return t;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n=postorder.size();
if(n==0)
return NULL;
TreeNode *t=tree(postorder,inorder,0,n-1,0,n-1);
return t;
}
};