1127 ZigZagging on a Tree PAT甲级

前中后序的相互转换只需要考虑对应的子树是否存在节点即可,有中序的顺序判断子树关系,由前(开始为根)或后(末尾为根)序遍历判断当前子树的根是哪个节点;

  

#include<iostream>
#include<vector>

using namespace std;
vector<int>in, pre, ans[10];
int pos[100]; 
int n;
void dfs(int node, int d,int l,int r,int index) {
	ans[d].push_back(node);
	if (r<=l) return;
	if (index - r + pos[node] -1>= 1&&pos[node]-l>=1)
		dfs(pre[index - r + pos[node]-1],d+1, l,pos[node]-1, index - r + pos[node]-1);
	if ( pos[node]<r && index - 1 >= 1)
		dfs(pre[index-1], d + 1, pos[node] + 1, r, index - 1);
}
int main()
{
	cin >> n;
	in.resize(n + 1), pre.resize(n+1);
	for (int i = 1; i <= n; i++) {
		cin >> in[i];
		pos[in[i]] = i;
	}
	for (int i = 1; i <= n; i++) {
		cin >> pre[i];
	}
	dfs(pre[n], 1, 1, n, n);
	int d = 2;
	printf("%d",ans[1][0]);
	while (ans[d].size() > 0) {
		if (d % 2 == 0) {
			for (int i = 0; i < ans[d].size(); i++)
				printf(" %d", ans[d][i]);
		}
		else {
			for (int i = ans[d].size() - 1; i >= 0; i--)
				printf(" %d", ans[d][i]);
		}
			d++;
	}
	getchar();
	getchar();
	return 0;
}

  

原文地址:https://www.cnblogs.com/zxzmnh/p/11709986.html