Idea:
The idea of this question is very clear. We all know that the first node of the preorder is the current root node, and then use this root node x to split the in-order array, because the element of the in-order array x The left subtree is the left subtree, and the right subtree is the right subtree; at the end is the loop recursion.
Code:
/**
* 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:
typedef vector<int>::iterator Iterator;
TreeNode* dfs(Iterator it1,int len1,Iterator it2,int len2){
int now = (*it1);
TreeNode* root = new TreeNode(now);
if(len1==1) return root;
Iterator bk = it2;
int i=1;
while(i<=len2){
if((*bk)==now) break;
++i;
++bk;
}
if(i-1>=1) root->left = dfs(it1+1,i-1,it2,i-1);
if(len2-i>=1) root->right = dfs(it1+i,len2-i,++bk,len2-i);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size() == 0 || inorder.size()==0) return 0;
return dfs(preorder.begin(),preorder.size(),inorder.begin(),inorder.size());
}
};