您的位置:首页 > 其它

团体程序设计天梯赛-练习集 L2-006. 树的遍历

2016-07-05 17:57 302 查看
团体程序设计天梯赛-练习集

L2-006. 树的遍历

https://www.patest.cn/contests/gplt/L2-006

按后序遍历来分治中序遍历,再推出所在层次。

#include<iostream>
#include<cstdio>
using namespace std;
int N,z;
int hou[35], zhong[35], cen[35];
void findc(int s, int d,int cnt) {
if (s > d) {
return;
}
if (z < 0) {
return;
}
for (int i = s; i <= d; i++) {
if (zhong[i] == hou[z]) {
cen[i] = cnt;
z--;
findc(i + 1, d, cnt + 1);
findc(s, i - 1, cnt + 1);
break;
}
}
}
int main() {
while (scanf("%d\n", &N) != EOF) {
for (int i = 0; i < N; i++) {
scanf("%d", &hou[i]);
}
for (int i = 0; i < N; i++) {
scanf("%d", &zhong[i]);
}
z = N - 1;
findc(0, N - 1, 0);
for (int i = 0, k = 0; k < N; i++) {
for (int j = 0; j < N; j++) {
if (cen[j] == i) {
k++;
printf(i ? " %d" : "%d", zhong[j]);
}
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: