PAT 1119 Pre- and Post-order Traversals

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.
在这里插入图片描述
题解:
题目大意:给了树的前后序遍历,输出中序遍历,若遍历不唯一,输出No和其中一个答案即可。
可以根据任意一个序列确定根节点,但如何结合前后序列确定左右子树边界?如何判断这棵树不唯一呢?这是这个题的难点。
在这里插入图片描述
分析可以得到,在前序里,1是根节点,2是左子树根节点;在后序里,3是右子树根节点,**通过两个子树根节点的位置可以判断出左右子树的结点个数,**通过递归可以输出中序序列。
这个问题很容易解决,但是如何解决判断该子树是否唯一呢?
这里我其实不太清楚,但根据给的两个案例,我做了一个大胆的预测,若前序根节点的紧跟着的左子树根节点在后序遍历里还是右子树根节点的话,那就不唯一(当时其实没有想得这么清晰,通过后想想应该是这么回事)
代码:

#include<iostream>
#include<vector>
using namespace std;
int pre[39],post[39];
vector<int> in;
bool flag=true;
void inorder(int preL,int preR,int postL,int postR){
	if(preL>preR) return;
	int root=pre[preL]; //记下根节点的值
	int rroot=preL+1;
	while(rroot<=preR&&pre[rroot]!=post[postR-1]) rroot++; //找到右子树在前序序列的位置
	int numL=rroot-preL-1;
	if(preL+1<=preR&&postR-1>=postL&&pre[preL+1]==post[postR-1]) flag=false;
	inorder(preL+1,rroot-1,postL,postL+numL-1);
	in.push_back(root);
	inorder(rroot,preR,postL+numL,postR-1);
}
int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) cin>>pre[i];
	for(int i=1;i<=n;i++) cin>>post[i];
	inorder(1,n,1,n);
	if(flag) printf("Yes\n");
	else printf("No\n");
	for(int i=0;i<in.size();i++) printf("%d%s",in[i],i==in.size()-1?"\n":" ");
	return 0;
}

在这里插入图片描述
其实在第一次提交的时候发现全部显示格式错误,我看了看测试区,好像就只在最后少了一个换行,调了一下后发现哦还真是这里的原因啊。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值