struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *buildTree(vector<int> &preorder, int i, int j, vector<int> &inorder, int m, int n) {
if (j <= i) return NULL;
int val = preorder[i];
TreeNode *node = new TreeNode(val);
int index = m;
while(index < n && inorder[index] != val) ++index;
if (index == n) {
return NULL;
}
node->left = buildTree(preorder, i+1, index-m+i+1, inorder, m, index);
node->right = buildTree(preorder, index-m+i+1, j, inorder, index+1, n);
return node;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
buildTree(preorder, 0, preorder.size(), inorder, 0, inorder.size());
}