class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
return create(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
}
TreeNode *create(vector<int>pre,vector<int>in,int preL,int preR,int inL,int inR)
{
if(preL>preR)return NULL;
TreeNode*root=new TreeNode(pre[preL]);
int k;
for(k=inL;k<=inR;k++){if(in[k]==root->val)break;}
int numleft=k-inL;
root->left=create(pre,in,preL+1,preL+numleft,inL,k-1);
root->right=create(pre,in,preL+numleft+1,preR,k+1,inR);
return root;
}
};
网友评论