因为要层序遍历,所以我们可以考虑构建一颗二叉树。构建完只有利用队列就可以就行层序遍历。
#include <bits/stdc++.h>
using namespace std;
int p1[35];
int p2[35];
typedef struct Tree {int val;struct Tree* left;struct Tree* right;
}TT;
typedef TT* TTT;
TTT add(int front1,int last1,int front2,int last2){TTT root=new TT;root->val=p1[last1];root->left=root->right=NULL;int p=front2;while(p2[p]!=p1[last1] ){p++;}int num=p-front2;if(p!= front2){root->left=add(front1,front1+num-1,front2,p-1);}if(p!= last2){root->right=add(front1+num,last1-1,p+1,last2);}return root;
}
void visit(TTT root){queue<TTT> Q;if(root){Q.push(root);}while(! Q.empty()){root=Q.front();Q.pop();cout<<root->val;if(root->left!=NULL){Q.push(root->left);}if(root->right!=NULL){Q.push(root->right);}if(! Q.empty()){cout<<' ';}}}
int main(){int n;cin>>n;for(int i=0;i<n;i++){cin>>p1[i];}for(int i=0;i<n;i++){cin>>p2[i];}TTT root=add(0,n-1,0,n-1);visit(root);return 0;
}