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
思路
build函数就是一个dfs的过程,不用另写dfs了
cpp代码
#include<iostream>
#include<unordered_map>
using namespace std;
const int N=50010;
int r[N],l[N];
int pre[N],in[N];
int pos;
int n;
unordered_map<int,int> Hash;
void build(int inl,int inr,int prel,int prer){
int root=pre[prel];
//if(inl>=inr)return ;第一个找到的叶子节点就是结果,这里return找到的就不是叶子节点了,而是叶子节点的父节点
int idx=Hash[root];
if(idx>inl)build(inl,idx-1,prel+1,(idx-1-inl)+prel+1);
if(idx<inr)build(idx+1,inr,(idx-1-inl)+prel+1+1,prer);
if(!pos)pos=root;
}
int main(){
cin>>n;
for(int i=0;i<n;i++)cin>>pre[i];
for(int i=0;i<n;i++)cin>>in[i],Hash[in[i]]=i;
build(0,n-1,0,n-1);
// dfs(root);这里dfs会段错误
cout<<pos<<endl;
return 0;
}