Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int *po = &postorder[0];
int *in = &inorder[0];
return build(po, in, inorder.size());
}
TreeNode *build(int *po, int *in, int n) {
if(n == 0) return nullptr;
TreeNode *root = new TreeNode(po[n-1]);
int i = 0;
for(; i<n; i++) {
if(in[i] == po[n-1]) break;
}
root->left = build(po, in, i);
root->right = build(po+i, in+i+1, n-i-1);
return root;
}