题目
https://pintia.cn/problem-sets/994805342720868352/problems/994805349394006016
题意
给出一棵树的中序和后序序列,要求按Z字型输出该数的层序序列
代码解析
详见参考文章,里面博主说的很详细了,在此解释一下df函数中的第一个参数index:
因为是地址传递,所以这个参数相当于先把postr赋值给root,然后在下一层递归时把root的左孩子和右孩子赋值给tree[index][0]和tree[index][1],以此类推。所以即使没有赋值语句,但执行完dfs后就完成了对tree数组的赋值
AC代码
#include<bits/stdc++.h>
using namespace std;
int post[35],in[35];
vector<int> res[35];
int n,root,tree[35][2];
struct node{
int index,depth;
};
void dfs(int &index,int inl,int inr,int postl,int postr)
{
if(inl>inr) return;
index=postr;// 为上一层index对应的地址赋值
int i=0;
while(in[i]!=post[postr]) i++;//找到根的位置
dfs(tree[index][0],inl,i-1,postl,postl+(i-inl)-1);
dfs(tree[index][1],i+1,inr,postl+(i-inl),postr-1);
}
void bfs()
{
queue<node> q;
q.push({root,0});
while(!q.empty())
{
node tmp=q.front();
q.pop();
res[tmp.depth].push_back(post[tmp.index]);
if(tree[tmp.index][0])
q.push({tree[tmp.index][0],tmp.depth+1});
if(tree[tmp.index][1])
q.push({tree[tmp.index][1],tmp.depth+1});
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++) cin>>in[i];
for(int i=1;i<=n;i++) cin>>post[i];
dfs(root,1,n,1,n);
bfs();
cout<<res[0][0];
for(int i=1;i<35;i++)
{
if(i%2)
for(int j=0;j<res[i].size();j++)
cout<<" "<<res[i][j];
else
for(int j=res[i].size()-1;j>=0;j--)
cout<<" "<<res[i][j];
}
}