/**
* 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* buildTree(vector<int>& inorder, vector<int>& postorder) {
int pos = postorder.size() - 1;
return buildBinary(inorder, postorder, 0, postorder.size() - 1, pos);
}
private:
TreeNode* buildBinary(vector<int>& inorder, vector<int>& postorder, int left, int right, int& pos) {
if (pos < 0 || left > right) {
return NULL;
}
int i = 0;
for (i = left; i <= right; i++) {
if (inorder[i] == postorder[pos]){
break;
}
}
TreeNode* node = new TreeNode(postorder[pos]);
pos--;
node->right = buildBinary(inorder, postorder, i + 1, right, pos);
node->left = buildBinary(inorder, postorder, left, i - 1, pos);
return node;
}
};