1119. Pre- and Post-order Traversals (30)

来源:互联网 发布:卖家淘宝发货回复大全 编辑:程序博客网 时间:2024/05/27 00:46

思路很容易想,有点小错误不好找

还有就是当n=1时,要单独讨论,不然会有一个两分的检测点不通过

#include<iostream>#include<vector>using namespace std;const int MAX = 40;int pre[MAX],post[MAX];vector<int> inbypre,inbypost;//通过post-order倒数第二个节点是pre-order右子树的第一个节点 void buildinbypost(int prel,int prer,int postl,int postr){int k;//在pre中找到右节点的下标for(int i=prel;i<=prer;i++){if(pre[i]==post[postr-1]){k=i;}}//根据pre-order中右子树根节点左边是左子树节点,当左子树节点只有一个时,即左孩子if(prel+1==k-1){inbypost.push_back(pre[prel+1]);//in-order左孩子先入; }else if(prel+1<k-1){int numleft=k-prel-1;//左子树中节点个数buildinbypost(prel+1,k-1,postl,postl+numleft-1);//递归左子树 }inbypost.push_back(pre[prel]);//in-order根节点入//考虑右子树if(k==prer){inbypost.push_back(pre[k]);//右子树节点只有一个 , }else if(k<prer){int numright=prer-k+1;//右子树节点个数buildinbypost(k,prer,postr-1-numright+1,postr-1);//递归右子树 }  }//根据pre-order第二节点是post-order左子树的最后一个节点 void buildinbypre(int prel,int prer,int postl,int postr){int k;//找到左子树最后一个节点在post-order中的位置 for(int i=postl;i<=postr;i++){if(pre[prel+1]==post[i]){k=i;}}if(k==postl){inbypre.push_back(post[k]);}else if(postl<k){int numleft=k-postl+1;buildinbypre(prel+1,prel+1+numleft-1,postl,k);}inbypre.push_back(post[postr]);//post[postr]if(k+1==postr-1){inbypre.push_back(post[k+1]);} else if(k+1<postr-1){int numright=postr-1-k;buildinbypre(prer-numright+1,prer,k+1,postr-1);}}int main(){int n;cin>>n;for(int i=0;i<n;i++){cin>>pre[i];}for(int i=0;i<n;i++){cin>>post[i];}if(n==1){   printf("Yes\n%d\n",pre[0]);}else{buildinbypre(0,n-1,0,n-1);    buildinbypost(0,n-1,0,n-1);    if(inbypre==inbypost){   printf("Yes\n%d",*(inbypre.begin()));   for(int i=1;i<inbypre.size();i++){   printf(" %d",inbypre[i]);    }   printf("\n");    }    else{   printf("No\n%d",*(inbypost.begin()));   for(int i=1;i<inbypost.size();i++){   printf(" %d",inbypost[i]);    }   printf("\n");    }}return 0;} 


0 0
原创粉丝点击