这是我参考其他人解答、修改之后的代码。我一开始是先”建树“,后postorder;其实可以合并在一起;而且可以在输出postorder第一个元素后提前结束。
#include <cstdio>
#include <vector>
int N;
std::vector<int> pre, in;
bool flag = false;
void post(int preL, int preR, int inL, int inR) {
if (preL > preR || flag) {
return;
}
int middle;
for (int i = inL; i <= inR; ++i) {
if (in[i] == pre[preL]) {
middle = i;
break;
}
}
post(preL + 1, preL + middle - inL, inL, middle - 1);
post(preL + middle - inL + 1, preR, middle + 1, inR);
if (!flag) {
printf("%d", pre[preL]);
flag = true;
}
}
int main() {
scanf("%d", &N);
pre.resize(N);
in.resize(N);
for (int i = 0; i < N; ++i) {
scanf("%d", &pre[i]);
}
for (int i = 0; i < N; ++i) {
scanf("%d", &in[i]);
}
post(0, N - 1, 0, N - 1);
return 0;
}
题目如下:
Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.