给出先序和后续,重建二叉树
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
TreeNode* ans=solve(pre,0,(int)pre.size(),in,0,(int)in.size());
return ans;
}
struct TreeNode* solve(vector<int>pre,int s,int e,vector<int>in,int ss,int ee)
{
if(s==e)
{
TreeNode * ans=NULL;
return ans;
}
TreeNode * ans=new TreeNode(pre[s]);
if(s==e-1) return ans;
int i;
for(i=ss;i<ee;i++)
if(in[i]==pre[s])
break;
int len=i-ss;
ans->left=solve(pre,s+1,s+len+1,in,ss,i);
ans->right=solve(pre,s+len+1,e,in,ss+len+1,ee);
return ans;
}
};