首页 > 学院 > 开发设计 > 正文

PAT A1119. Pre- and Post-order Traversals (30)

2019-11-06 06:31:13
字体:
来源:转载
供稿:网友

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or PReorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.

Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first printf in a line "Yes" if the tree is unique, or "No" if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input 1:
71 2 3 4 6 7 52 6 7 4 5 3 1Sample Output 1:
Yes2 1 6 4 7 3 5Sample Input 2:
41 2 3 42 4 3 1Sample Output 2:
No2 1 3 4
#include <cstdio>#include<algorithm>#include<vector>using namespace std;const int Max = 40;int n;int pre[Max]={0},post[Max]={0};vector<int> In;int findRoot(int x,int preL,int preR){	int i;	for(int i=preL;i<=preR;i++)	{		if(x==pre[i])			return i;	}	return -1;}int u=1;void Makeit(int preL,int preR,int postL,int postR){	if(preL==preR)	{		In.push_back(pre[preL]);		return ;	}	if(pre[preL]==post[postR])	{		int img=findRoot(post[postR-1],preL+1,preR);		if(img-preL>1)//说明这个为其有孩子,则唯一		{			Makeit(preL+1,img-1,postL,postL-preL+img-2);			In.push_back(post[postR]);			Makeit(img,preR,postL-preL+img-1,postR-1);		}		else		{			u=0;			In.push_back(post[postR]);			Makeit(img,preR,postL-preL+img-1,postR-1);		}	}}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",&post[i]);	Makeit(0,n-1,0,n-1);	printf("%s/n",u?"Yes":"No");	for(int i=0;i<In.size();i++)	{		printf("%d",In[i]);		if(i<In.size()-1) printf(" ");		else printf("/n");	}	system("pause");	return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表