题目
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(\le50,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
思路
个人觉得测试点4有点坑,卡了半天一直超时,最终千辛万苦优化代码,终于找到了最佳方法,只需要遍历先序序列即可,无需遍历后序序列,具体见代码:
代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
using namespace std;
int main(){
int n;
vector<int> preorder, inorder;
vector<bool> visited;
map<int, int> mp;
scanf("%d", &n);
preorder.resize(n), inorder.resize(n), visited.resize(n);
for(int i=0; i<n; i++)
scanf("%d", &preorder[i]);
for(int i=0; i<n; i++){
scanf("%d", &inorder[i]);
mp[inorder[i]] = i;
visited[i] = false;
}
int k = 0,k1 = 0, k2 = n-1;
for(k=0; k1!=k2; k++){
int t = mp[preorder[k]];
if(t > k1)
k2 = t-1;
else if(t < k2)
k1 = t+1;
}
printf("%d\n", preorder[k]);
return 0;
}