题目描述:
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 6Sample Output:
3
这道题题目翻译出来很简单,给定一棵书的先序遍历和后序遍历,然后找出这棵树后序遍历的第一个元素,考察数据结构知识吧。我的思路是先找到根,然后不停找左子树,如果发现当前的根已经没有左子树了,就转而去找右子树的左子树,以此类推,知道找到叶子结点。代码如下:
#include<iostream>
using namespace std;
int main(){
int N;
cin>>N;
int pre[50001],in[50001];
int istra[50001]={0};
for(int i=0;i<N;i++)
cin>>pre[i];
for(int i=0;i<N;i++)
cin>>in[i];
int n=N,prep=0,start=0;
int ans=0;
while(true){
int i;
for(i=start;i<n;i++)
if(in[i]==pre[prep])
break;
if(i!=start) n=i;
istra[i]=1;
if((i-1==-1||istra[i-1]==1)&&(i+1==N||istra[i+1]==1)){
ans=i;
break;
}
if(i-1==-1||istra[i-1]==1)
start=i+1;
prep++;
}
cout<<in[ans];
return 0;
}