题意:
输入一个正整数N(<=30),接着输入两行分别为中序遍历和后序遍历,蛇形输出层次遍历。
AAAAAccepted code:
1 #define HAVE_STRUCT_TIMESPEC 2 #include<bits/stdc++.h> 3 using namespace std; 4 typedef struct node{ 5 int num; 6 int level; 7 node *lc,*rc; 8 }; 9 int root; 10 int in[37],post[37]; 11 int num[37][5]; 12 pair<int,int>ans[37]; 13 void dfs(int &index,int l,int r,int L,int R){ 14 if(l>r) 15 return ; 16 int pos=0; 17 while(in[pos]!=post[R]) 18 ++pos; 19 index=R; 20 dfs(num[index][0],l,pos-1,L,L+pos-1-l); 21 dfs(num[index][1],pos+1,r,L+pos-l,R-1); 22 return ; 23 } 24 int main(){ 25 ios::sync_with_stdio(false); 26 cin.tie(NULL); 27 cout.tie(NULL); 28 int n; 29 cin>>n; 30 for(int i=1;i<=n;++i) 31 cin>>in[i]; 32 for(int i=1;i<=n;++i) 33 cin>>post[i]; 34 dfs(root,1,n,1,n); 35 int flag=0; 36 queue<pair<int,int> >q; 37 q.push({root,0}); 38 int cnt=0; 39 while(!q.empty()){ 40 pair<int,int>now=q.front(); 41 q.pop(); 42 ans[++cnt]={post[now.first],now.second}; 43 if(num[now.first][0]) 44 q.push({num[now.first][0],now.second+1}); 45 if(num[now.first][1]) 46 q.push({num[now.first][1],now.second+1}); 47 } 48 cout<<ans[1].first; 49 for(int i=2;i<=cnt;++i){ 50 if(ans[i].second&1) 51 cout<<" "<<ans[i].first; 52 else{ 53 int pos=cnt; 54 for(int j=i+1;j<=cnt;++j) 55 if(ans[j].second&1){ 56 pos=j-1; 57 break; 58 } 59 for(int j=pos;j>=i;--j) 60 cout<<" "<<ans[j].first; 61 i=pos; 62 } 63 } 64 return 0; 65 }