-----QUESTION-----
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
-----SOLUTION-----
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
root = NULL;
if(inorder.empty()) return root;
root = new TreeNode(0);
buildSubTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1,root);
return root;
}
void buildSubTree(vector<int> &inorder, vector<int>&postorder, int inStartPos, int inEndPos, int postStartPos, int postEndPos,TreeNode * currentNode)
{
currentNode->val = postorder[postEndPos];
//find root position in inorder vector
int inRootPos;
for(int i = inStartPos; i <= inEndPos; i++)
{
if(inorder[i] == postorder[postEndPos])
{
inRootPos = i;
break;
}
}
//right tree
int newPostPos = postEndPos - max(inEndPos - inRootPos, 0);
if(inRootPos<inEndPos)
{
currentNode->right = new TreeNode(0);
buildSubTree(inorder,postorder,inRootPos+1,inEndPos,newPostPos,postEndPos-1,currentNode->right);
}
//leftTree
if(inRootPos>inStartPos)
{
currentNode->left = new TreeNode(0);
buildSubTree(inorder,postorder,inStartPos,inRootPos-1,postStartPos,newPostPos-1,currentNode->left);
}
}
private:
TreeNode* root;
};