【题解】【AcWing】1620. Z 字形遍历二叉树

134 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1620. Z 字形遍历二叉树

原题传送:AcWing 1620. Z 字形遍历二叉树

假设一个二叉树上各结点的权值互不相同。

我们就可以通过其后序遍历和中序遍历来确定唯一二叉树。

请你输出该二叉树的 ZZ 字形遍历序列----也就是说,从根结点开始,逐层遍历,第一层从右到左遍历,第二层从左到右遍历,第三层从右到左遍历,以此类推。

例如,下图所示二叉树,其 ZZ 字形遍历序列应该为:1 11 5 8 17 12 20 15

输入格式

第一行包含整数 NN ,表示二叉树结点数量。

第二行包含 NN 个整数,表示二叉树的中序遍历序列。

第三行包含 NN 个整数,表示二叉树的后序遍历序列。

输出格式

输出二叉树的 ZZ 字形遍历序列。

数据范围

1N301 \le N \le 30

输入样例:

8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1

输出样例:

1 11 5 8 17 12 20 15

思路:

中序遍历和后序遍历构造树,bfs输出时判断层数的奇偶性决定是否反向输出。

题解:

#include<bits/stdc++.h>

using namespace std;

const int N = 40;

int n;
int post[N], in[N];
unordered_map<int, int> l, r, pos;
int q[N];

int build(int il, int ir, int pl, int pr)
{
	int root = post[pr];
	int k = pos[root];
	if(il < k)
		l[root] = build(il, k - 1, pl, pl + (k - 1 - il));
	if(k < ir)
		r[root] = build(k + 1, ir, pl + (k - 1 - il) + 1, pr - 1);
	return root;
}

void bfs(int root)
{
	int hh =  0, tt = 0;
	q[0] = root;
	
	int step = 0;
	while(hh <= tt)
	{
		int head = hh, tail = tt;
		while(hh <= tail)
		{
			int t = q[hh++];
			if(l.count(t))
				q[++tt] = l[t];
			if(r.count(t))
				q[++tt] = r[t];
		}
		if(++step % 2)
			reverse(q + head, q + tail + 1);
	}
}

int main()
{	
	cin >> n;
	
	for(int i = 0; i < n; i++)
		cin >> in[i];
	for(int i = 0; i < n; i++)
	{
		cin >> post[i];
		pos[in[i]] = i;
	}
		
	int root = build(0, n - 1, 0, n - 1);
	
	bfs(root);
	
	cout << q[0];
	for(int i = 1; i < n; i++)
		cout << " " << q[i];
	cout << endl;
	
	return 0;
}