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.
Sample Input:
7
1 2 3 4 5 6 7
2 3 1 5 4 7 6
Sample Output:
3
这题考察的非常基础,就是知道俩个序列,然后求第三个序列,这题,如果不设置flag会有俩个点超时,只会得20分
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 5e4;
int pre[N];
int in[N];
vector<int>p;
bool flag = false;
void po(int l1, int r1, int l2, int r2)
{
if (l1 > r1 || l2 > r2||flag==true) {
//flag = true;
return;
}
int mid=0;
while (in[mid] != pre[l1])
{
mid++;
}
po(l1 + 1, l1 + (mid - l2), l2, mid - 1);
po(l1 + (mid - l2) + 1, r1, mid + 1, r2);
if (flag == false) {
printf("%d\n", pre[l1]);
flag = true;
}
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0;i < n;i++) scanf("%d", &pre[i]);
for (int i = 0;i < n;i++) scanf("%d", &in[i]);
po(0, n - 1, 0, n - 1);
return 0;
}