1. 程式人生 > >1138. Postorder Traversal (25)【已知前序和中序求後序】

1138. Postorder Traversal (25)【已知前序和中序求後序】

1138. Postorder Traversal (25)

時間限制 600 ms
記憶體限制 65536 kB
程式碼長度限制 16000 B
判題程式 Standard 作者 CHEN, Yue

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

題解

#include <bits/stdc++.h>
#include<vector>
#define ms(x,y) memset(x,y,sizeof(x))
const int M=1e4+10;
using namespace std;
int j,k,n,m,q;
vector<int> pre, in;
bool flag=0;

void post(int prel,int inl,int inr)
{
    if(inl>inr||flag)return;
    int i=inl;
    while(in[i]!=pre[prel])i++;
    post(prel+1,inl,i-1);
    post(prel+i-inl+1,i+1,inr);
    if(!flag){
        printf("%d\n",in[i]);
        flag=1;
    }
}

int main()
{
    scanf("%d",&n);
    pre.resize(n);in.resize(n);
    for(int i=1;i<=n;i++)scanf("%d",&pre[i]);
    for(int i=1;i<=n;i++)scanf("%d",&in[i]);
    post(1,1,n);
    return 0;
}