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