PAT-A 真题 – 1138 Postorder Traversal

发布于 / PAT-甲级 / 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.

Sample Input:

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

Sample Output:

3

题目大意:给定二叉树的前序、中序序列,输出后续序列的第一个

这道题不用建树,看看有没有左子树,如果有,找左子树,如果没有,找右子树,递归找,找到头,就是后续序列第一个了。

#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> mp;
vector<int> pre, in;

int get(int preL, int preR, int inL, int inR){
  if(preL == preR) return pre[preL];
  if(pre[preL] == in[inL])  //没有左子树
    return get(preL + 1, preR, inL + 1, inR);  //找右子树
  int root = pre[preL], lchild_len = mp[root] - inL; 
  return get(preL + 1, preL + lchild_len, inL, inL + lchild_len - 1);  //找左子树 
}

int main(){
  int cnt;
  cin >> cnt;
  pre.resize(cnt), in.resize(cnt);
  for(int & i : pre) cin >> i;
  for(int i = 0; i < cnt; i++){
    cin >> in[i];
    mp[in[i]] = i;
  }
  cout << get(0, cnt-1, 0, cnt-1) << endl;
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题 – 1138 Postorder Traversal
目前还没有评论,快来抢沙发吧~