1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include <cstdio> #include <queue> using namespace std; const int maxn=50; struct Node{ int data; Node* left; Node* right; Node(int d=0,Node* l=NULL,Node* r=NULL):data(d),left(l),right(r){} }; Node* Root; int n; int in[maxn]; int post[maxn];
void create(Node* &root,int l1,int r1,int l2,int r2){ if(l1>r1||l2>r2) return; root=new Node(post[r1]); int p=r2; while(l2<=p){ if(in[p]==post[r1]) break; p--; } create(root->left,l1,l1+p-l2-1,l2,p-1); create(root->right,r1-r2+p,r1-1,p+1,r2); } void dfs(){ queue<Node*> q; printf("%d",Root->data); if (Root->left) q.push(Root->left); if (Root->right) q.push(Root->right); while(!q.empty()){ Node* u=q.front(); q.pop(); printf(" %d",u->data); if (u->left) q.push(u->left); if (u->right) q.push(u->right); } } int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&post[i]); for(int i=0;i<n;i++) scanf("%d",&in[i]); create(Root,0,n-1,0,n-1); dfs(); return 0; }
|