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
题目大意:给出一棵有n个节点,且所有节点值都不同的二叉树的前序和中序遍历,输出它的后序遍历序列的第一个数。
分析:其实不需要先建树在去后序遍历。不妨假设最简单的情况。
1、根节点没有孩子。此时它的后序遍历序列第一个数就是它自己;
2、根节点有左孩子。由于后序遍历从左子树开始,有没有右子树对于后序遍历的第一个数没有影响。此时它的后序遍历序列第一个数就是它的左孩子;
3、根节点只有右孩子。此时它的后序遍历序列第一个数就是它的右孩子;
推广到整棵树,也就是遍历的时候,只要看当前节点是上面3中情况的哪一种即可。
#include<algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <ctime>
#include <cmath>
#include <map>
#include <set>
#define INF 0xffffffff
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<endl
#define db5(x,y,z,r,w) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<", "<<#w<<"="<<(w)<<endl
using namespace std;
void getans(int *preorder,int pl,int pr,int *inorder,int il,int ir)
{
int root=preorder[pl],index;
for(index=il;index<ir;++index)//在中序遍历里找根节点
if(inorder[index]==root)break;
if(index>il)//如果当前的节点有左子树,去左子树里找
getans(preorder,pl+1,pl+1+index-il,inorder,il,index);
else if(ir==il+1)//当前节点是叶子,说明找到了
{
printf("%d\n",inorder[index]);return;
}
else//当前节点没有左子树,也不是叶子,就去右子树里找
getans(preorder,pl+1,ir-il,inorder,index+1,ir);
}
int main(void)
{
#ifdef test
freopen("in.txt","r",stdin);
//freopen("in.txt","w",stdout);
clock_t start=clock();
#endif //test
int n;scanf("%d",&n);
int preorder[n+5]={0},inorder[n+5]={0};
for(int i=0;i<n;++i)scanf("%d",&preorder[i]);
for(int i=0;i<n;++i)scanf("%d",&inorder[i]);
getans(preorder,0,n,inorder,0,n);
#ifdef test
clockid_t end=clock();
double endtime=(double)(end-start)/CLOCKS_PER_SEC;
printf("\n\n\n\n\n");
cout<<"Total time:"<<endtime<<"s"<<endl; //s为单位
cout<<"Total time:"<<endtime*1000<<"ms"<<endl; //ms为单位
#endif //test
return 0;
}