PAT 甲级 1138 Postorder Traversal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a845717607/article/details/87983767

1138 Postorder Traversal (25 point(s))

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

经验总结:

emmm 经典的前序中序转后序问题,千万不要再利用前序和中序建立一个树,然后再遍历树了,这一题有一个测试点非常接近超时边界,最好的方式是找到后序序列的第一个数就输出,并且停止继续查找,这里用一个全局变量就可以实现了~

AC代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <map>
using namespace std;
const int maxn=50010;
int n,m,p,t,pre[maxn],in[maxn];
bool flag=false;
void getpost(int preL,int preR,int inL,int inR)
{
	if(preL>preR||flag==true)
		return ;
	int index;
	for(index=inL;index<=inR;++index)
		if(in[index]==pre[preL])
			break;
	getpost(preL+1,preL+index-inL,inL,index-1);
	if(flag==true)
		return ;
	getpost(preL+index-inL+1,preR,index+1,inR);
	if(flag==false)
	{
		flag=true;
		printf("%d",pre[preL]);
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=0;i<n;++i)
		scanf("%d",&pre[i]);
	for(int i=0;i<n;++i)
		scanf("%d",&in[i]);
	getpost(0,n-1,0,n-1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/87983767
今日推荐