PAT_A_1119 Pre- and Post-order Traversals

题意:根据先序和后序求任意中序

思路:先序和中序或者后序和中序能够唯一确定一个二叉树,但是先序和后序遍历却不能唯一确定,题目中说任意打印一种情况即可,那剩下就是左子树和右子树划分的问题了

代码:

#include<iostream>
#include<vector>
using namespace std;
vector<int> pre, in, post;
bool unique = true;
void getIn(int preL,int preR,int postL,int postR) {
	if (preL == preR) {
		in.push_back(pre[preL]);
		return;
	}
	if (pre[preL] == post[postR]) {//表示前序遍历的根节点与后续遍历的根节点相同
		int i = preL + 1;
		while (i < pre.size() && pre[i] != post[postR-1])i++;//找到右子树的根节点
		if (i - preL > 1) {//左子树不止一个节点时
			getIn(preL + 1, i - 1, postL, postL + (i - 1 - (preL + 1)));//把左子树压入中序遍历中
		}
		else {
			unique = false;
		}
		in.push_back(post[postR]);//把根节点压入中序遍历
		getIn(i,preR, postL + (i - 1 - (preL + 1))+1,postR-1); //把以右子树压入中序遍历中
	}
}
int main() {
	int n = 0;
	cin >> n;
    post.resize(n+1);
	pre.resize(n + 1);
	for (int i = 0; i < n; i++) scanf("%d", &pre[i]);
	for (int i = 0; i < n; i++) scanf("%d", &post[i]);
	getIn(0, n - 1, 0, n - 1);
	if (unique) {
		cout << "Yes" << endl << in[0];
	}
	else {
		cout << "No" << endl << in[0];
	}
	for (int i = 1; i < in.size(); i++) {
		cout << " " << in[i];
	}
	printf("\n");
	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值