PAT 1138. Postorder Traversal (25)

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 (<=50000), 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.

Sample Input:

7
1 2 3 4 5 6 7
2 3 1 5 4 7 6

Sample Output:

3

前序中序转后序,考试的时候还以为姥姥不会出这种题目了呢。 输出后序的第一个结点就可以了,只需在前序中序转后序的代码里面加上一个变量就可以了。见代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <cstdio>

int *pre, *in;

bool isOuput = false;

int find(int inl, int inr, int x) {
for (int i = inl; i <= inr; i++) {
if (in[i] == x) return i;
}
return -1;
}

void printPost(int pl, int pr, int inl, int inr, int n) {
if (pl > pr || isOuput) return;
int inRoot = find(inl, inr, pre[pl]);
printPost(pl + 1, pl + inRoot - inl, inl, inRoot - 1, n);
printPost(pl + inRoot - inl + 1, pr, inRoot + 1, inr, n);
if (!isOuput) {
printf("%d", in[inRoot]);
isOuput = true;
}
}

int main() {
int n = 0;
scanf("%d", &n);
pre = new int[n];
in = new int[n];
for (int i = 0; i < n; i++) {
scanf("%d", &pre[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
printPost(0, n - 1, 0, n - 1, n);
delete[] pre;
delete[] in;
return 0;
}