Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return myBT2(postorder.size() - 1,postorder,0,inorder.size() - 1,inorder);
}
TreeNode * myBT2(int postID,vector<int>& postorder,int inID,int inEnd,vector<int>& inorder){
if(postID < 0 || inID > inEnd) return NULL;
TreeNode * root = new TreeNode(postorder[postID]);
int i;
for(i = inID; i <= inEnd; i ++ ){
if(inorder[i] == postorder[postID])
break;
}
root->left = myBT2(postID - (inEnd - i) - 1 ,postorder,inID,i - 1,inorder);
root->right = myBT2(postID - 1,postorder,i + 1,inEnd,inorder);
return root;
}
};