CCCC团体程序设计天梯赛 L2-011 玩转二叉树

记录天梯赛题目合集 跳转查看

题目链接

题目描述

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:
输入第一行给出一个正整数\(N(≤30)\),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。

输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const ll inf = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 100 + 10;

int n, h;
int a[N], b[N];
vector<int> g[N];

void dfs(int r, int st, int ed, int idx)
{
	if (st > ed) return ;
	h = max(h, idx);
	g[idx].emplace_back(b[r]);
	int i;
	for (i = st; i <= ed; i ++)
		if (a[i] == b[r]) break;
	dfs(r + 1, st, i - 1, idx + 1);
	dfs(r + i - st + 1, i + 1, ed, idx + 1);
}

void solve()
{
	cin >> n;
	for (int i = 0; i < n; i ++) cin >> a[i];
	for (int i = 0; i < n; i ++) cin >> b[i];
	
	dfs(0, 0, n - 1, 0);
	
	vector<int> res;
	for (int i = 0; i <= h; i ++) {
		reverse(g[i].begin(), g[i].end());
		for (auto it : g[i])
			res.emplace_back(it);
	}
	
	for (int i = 0; i < n; i ++) {
		if (i) cout << ' ';
		cout << res[i];
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr), cout.tie(nullptr);
	
	int T = 1;
//	cin >> T;
	while (T --) solve();
	return 0;
}
posted @ 2025-08-17 09:55  Natural_TLP  阅读(11)  评论(0)    收藏  举报