#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>

using namespace std;
int z[30],h[30];
class Tree
{
public:
    int data;
    Tree *lchild;
    Tree *rchild;
    Tree()
    {
        lchild=NULL;
        rchild=NULL;
    }
}*root;
Tree *CreatNode()
{
    Tree *root=new Tree();
    return root;
}
Tree *RestoreTree(int z1,int z2,int h1,int h2)
{
    Tree *root=CreatNode();
    root->data=h[h2];
    for(int i=0;z2-i>=z1;i++)
    {
        if(z[z2-i]==h[h2])
        {
            if(i>0)root->rchild=RestoreTree(z2-i+1,z2,h2-i,h2-1);
            if(z2-i>z1)root->lchild=RestoreTree(z1,z2-i-1,h1,h2-i-1);
            break;
        }
    }
    return root;
}
void FDpostOrder(Tree *root)///非递归后序遍历。。更新了一下写法
{
    stack<Tree*>q;
    Tree *temp=root;
    Tree *p;
    while(temp!=NULL||!q.empty())
    {
        while(temp!=NULL)
        {
            q.push(temp);
            temp=temp->lchild;
        }
        if(q.top()->rchild!=NULL)///右儿子不为空,则入栈
        {
            temp=q.top()->rchild;
        }
        else
        {
            p = q.top();
            q.pop();
            cout<<p -> data<<' ';
            while(!q.empty() && (q.top() -> rchild == NULL || q.top() -> rchild == p))//栈不空是前提,右儿子为空或者右儿子入过栈了且已经出栈了满足输出条件。
            {
                p = q.top();
                q.pop();
                cout<<p -> data<<' ';
            }
        }
    }
}
void FDinOrder(Tree *root)
{
    stack<Tree*>q;
    Tree *temp=root;
    while(temp||!q.empty())///非递归中序遍历,及时栈空了,temp不空,仍然继续
    {
        while(temp!=NULL)
        {
            q.push(temp);
            temp=temp->lchild;
        }
        temp=q.top()->rchild;
        cout<<q.top()->data<<' ';
        q.pop();
    }
}
void FDpreOrder(Tree *root)///非递归前序遍历
{
    stack<Tree*>q;
    Tree *temp=root;
    while(temp||!q.empty())
    {
        while(temp!=NULL)
        {
            q.push(temp);
            cout<<temp->data<<' ';
            temp=temp->lchild;
        }
        temp=q.top()->rchild;
        q.pop();
    }
}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>h[i];
    for(int i=0;i<n;i++)
        cin>>z[i];
    root=RestoreTree(0,n-1,0,n-1);
    FDpreOrder(root);
    cout<<endl;
    FDinOrder(root);
    cout<<endl;
    FDpostOrder(root);
    cout<<endl;
    return 0;
}