思路:
/**
* 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) {
return Construct(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode *Construct(vector<int>& preorder,int s0,int e0,vector<int>& inorder,int s1,int e1){
if(s0 > e0 || s1 > e1) return NULL;
int rootval = preorder[s0];
int rootindex = find(inorder,s1,e1,rootval);
TreeNode* root = new TreeNode(rootval);
int leftsize = rootindex - s1 + 1;
root->left = Construct(preorder,s0+1,s0+leftsize-1,inorder,s1,rootindex-1);
root->right = Construct(preorder,s0+leftsize,e0,inorder,rootindex+1,e1);
return root;
}
int find(vector<int>& inorder,int s1,int e1,int rootval){
for(int i = s1; i <= e1; i++){
if(inorder[i] == rootval) return i;
}
return -1;
}
};