题目地址

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 <cstdio>
#include <cstring>
#include<iostream>
#include <vector>
#include<math.h>
#include<string>
#include<queue>
#include <algorithm>
#include<set>
#include<map>
using namespace std;
const int maxn=100010;
int n;
struct node{
    int data;
    node *lchild,*rchild;
};
int pre[maxn],in[maxn];
node *create(int pre_l,int pre_r,int in_l,int in_r){
    if(pre_l>pre_r||in_l>in_r) return NULL;
    node *root=new node;
    root->data=pre[pre_l];
    int k,num_left;
    for(k=in_l;k<=in_r;k++)
        if(in[k]==pre[pre_l]) break;
    num_left=k-in_l;
    root->lchild=create(pre_l+1,pre_l+num_left,in_l,k-1);
    root->rchild=create(pre_l+num_left+1,pre_r,k+1,in_r);
    return root;
}
bool flag=0;
void dfs(node *root){
    if(!root) return;
    dfs(root->lchild);dfs(root->rchild);
    if(!flag){
        cout<<root->data;flag=1;
    }
}
int main(){
    cin>>n;
    node *root;
    for(int i=0;i<n;i++) cin>>pre[i];
    for(int i=0;i<n;i++) cin>>in[i];
    root=create(0,n-1,0,n-1);
    dfs(root);
}