PAT 1127 ZigZagging on a Tree
作者:互联网
题解:
代码:
#include<iostream>
#include<vector>
using namespace std;
const int maxv=39;
vector<int> tree[maxv];
int in[maxv],post[maxv];
int layer=1;
void layertravel(int postL,int postR,int inL,int inR,int nowlayer){
if(layer<nowlayer) layer=nowlayer;
if(postL>=postR) return;
int k=inL;
while(in[k]!=post[postR]) k++;
int numL=k-inL;
if(numL!=0){
tree[nowlayer+1].push_back(post[postL+numL-1]); //左子节点
// cout<<nowlayer+1<<": "<<post[postL+numL-1]<<endl;
layertravel(postL,postL+numL-1,inL,k-1,nowlayer+1);//层序遍历左子树
}
if(postL+numL!=postR){
tree[nowlayer+1].push_back(post[postR-1]); //右子节点
// cout<<nowlayer+1<<": "<<post[postR-1]<<endl;
layertravel(postL+numL,postR-1,k+1,inR,nowlayer+1);//层序遍历左子树
}
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>in[i];
for(int i=1;i<=n;i++) cin>>post[i];
tree[1].push_back(post[n]);
layertravel(1,n,1,n,1);
for(int i=1;i<layer;i++){
if(i%2==0){
for(int j=0;j<tree[i].size();j++)
cout<<tree[i][j]<<" ";
}
else{
for(int j=tree[i].size()-1;j>=0;j--)
cout<<tree[i][j]<<" ";
}
}
//cout<<endl;
// cout<<tree[layer].size()<<endl;
if(layer%2==0){
for(int i=0;i<tree[layer].size();i++) printf("%d%s",tree[layer][i],i==tree[layer].size()-1?"\n":" ");
}
else{
for(int i=tree[layer].size()-1;i>=0;i--) printf("%d%s",tree[layer][i],i==0?"\n":" ");
}
return 0;
}
在第一次构建代码之前一定要想清楚再想清楚,不然会因为小错误及一些漏掉的地方浪费巨多时间。
标签:layer,PAT,int,tree,maxv,Tree,postR,post,ZigZagging 来源: https://blog.csdn.net/virtual_YL/article/details/114707957