PAT (Advanced Level) 1020 Tree Traversals

题意

后序遍历和中序遍历,求层序遍历。

思路

递归建树。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n;
	cin >> n;
	vector<int> rev(n), in(n);
	for (auto &e : rev) cin >> e;
	for (auto &e : in) cin >> e; 
	vector<pair<int, int>> son(n, {-1, -1});
	function<void(int, int, int, int)> dfs;
	dfs = [&](int revlo, int revhi, int inlo, int inhi) {
		int root = --revhi;
		int l_len = find(in.begin(), in.end(), rev[root]) - in.begin() - inlo;
		int r_len = revhi - revlo - l_len;
		if (l_len) {
			dfs(revlo, revlo + l_len, inlo, inlo + l_len);
			son[root].first = revlo + l_len - 1;
		}	
		if (r_len) {
			dfs(revhi - r_len, revhi, inhi - r_len, inhi);
			son[root].second = revhi - 1;
		}
	};
	dfs(0, n, 0, n);
	vector<int> ans;
	queue<int> q;
	for (q.push(n - 1); !q.empty(); q.pop()) {
		int u = q.front();
		ans.push_back(rev[u]);
		if (son[u].first != -1)
			q.push(son[u].first);
		if (son[u].second != -1)
			q.push(son[u].second);	
	}
	for (int i = 0; i < n; ++i)
		cout << ans[i] << (i == n - 1 ? '\n' : ' ');
	return 0;
} 

HINT

不定时更新更多题解,详见 git ! ! !

上一篇:PAT (Basic Level) 1020 月饼


下一篇:PTA乙级 (1020 月饼 (25分))