#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 35;
vector<int> level[maxn];
int in[maxn], post[maxn];
struct node
{
int data,level;
node *lchild, *rchild;
};
node* create(int inleft, int inright, int postleft, int postright,int index)
{
if (inleft > inright) return NULL;
node* root = new node;
root->data = post[postright];
root->level = index;
int k;
for (k = inleft; k <= inright; k++)
{
if (in[k] == post[postright]) break;
}
root->lchild = create(inleft, k - 1, postleft, postleft + k - 1 - inleft,index+1);
root->rchild = create(k + 1, inright, postright - 1 - (inright - k - 1), postright - 1,index+1);
return root;
}
void zigdfs(node* root)
{
queue<node*> q;
q.push(root);
while (!q.empty())
{
node* now = q.front();
q.pop();
//printf("%d ", now->data);
level[now->level].push_back(now->data);
if (now->lchild != NULL) q.push(now->lchild);
if (now->rchild != NULL) q.push(now->rchild);//这里是now啊,错写成root还发现不了。。
}
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &in[i]);
for (int i = 0; i < n; i++) scanf("%d", &post[i]);
node* root = create(0, n - 1, 0, n - 1, 0);
zigdfs(root);
int total = 0;
int p = 0;
while (level[p].size() != 0)
{
if (p % 2 == 1)
{
for (int j = 0; j < level[p].size(); j++)
{
printf("%d", level[p][j]);
total++;
if (total != n) printf(" ");
}
}
else
{
for (int j = level[p].size() - 1; j >= 0; j--)
{
printf("%d", level[p][j]);
total++;
if (total != n) printf(" ");
}
}
p++;
}
printf("\n");
return 0;
}
思路比较清晰,先建树然后遍历。由于z字形输出,设置一个vector来存放各个行的数字个数,分奇偶来判断输出。