这题和上题几乎一样,但却出了个RE的错误。
原因是,再求下标范围的时候偷懒,导致了越界。悔不当初!稍有疏忽,代价很大。
in1=i1; in2=mid-1; inL=mid+1; inR=i2; //split inorder into two subtree :left & right
pt1=p1; pt2=in2; ptL=pt2+1; ptR=p2-1;
偷懒直接把pt2=in2了,这两个只在树划分平衡时相等。正确应该是:
in1=i1; in2=mid-1; inL=mid+1; inR=i2; //split inorder into two subtree :left & right
pt1=p1; pt2=pt1+(in2-in1); ptL=pt2+1; ptR=p2-1;
严谨认真,否则就等着出错吧。变量的使用要注意,l和1实在太像了,这两个最好不要同时出现,而我却让他们出现了。
class Solution {
public:
TreeNode * subt(vector<int> &inorder,int i1,int i2, vector<int> &postorder,int p1,int p2){
if(i1>i2) return nullptr;
int mid=in[postorder[p2]];
int in1,in2,inl,inr;
int pt1,pt2,ptl,ptr;
in1=i1; in2=mid-1; inl=mid+1; inr=i2; //split inorder into two subtree :left & right
pt1=p1; pt2=pt1+in2-in1; ptl=pt2+1; ptr=p2-1;
TreeNode *root= new TreeNode(inorder[mid]);
root->left =subt(inorder,in1,in2,postorder,pt1,pt2);
root->right=subt(inorder,inl,inr,postorder,ptl,ptr);
return root;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if(!inorder.size()||!postorder.size()||inorder.size()!=postorder.size()) return nullptr;
int n=inorder.size();
for(int i=0; i<n ;++i){
in.insert(make_pair(inorder[i],i));
post.insert(make_pair(postorder[i],i));}
TreeNode * res= subt(inorder,0,n-1,postorder,0,n-1);
return res;
}
private:
unordered_map<int,int>in,post;
};