P1030 求先序排列

P1030

树形结构里的经典题,也是必备的入门题
首先,放上一个结论,如若想唯一确定一个树,必须得至少已知它的中序遍历,否则不管你哪怕知道前序、后序、层序遍历,也无法唯一确定一个树。

一、已知先序中序求后序

第一步,先序遍历第一个位置肯定是根节点,然后在中序遍历中确定该根结点的位置
第二步,确定好位置后,即可分别对左子树和右子树进行递归
在这里插入图片描述
具体左子树和右子树的一个范围下标在图中已经很明显了,就不再做多余解释。

直接干代码:

void post_order(int x, int y, int p, int q) {  //x~y为前序遍历 p~q为中序遍历
	if (x > y || p > q) return;//规定边界条件
	else {
		int root_pos = s2.find(s1[x]);   //利用根左右的特性来在中序队列中查找
		post_order(x + 1, x + root_pos - p, p, root_pos - 1);      //递归左子树
		post_order(x + root_pos - p + 1, y, root_pos + 1, q);      //递归右子树
		cout << s1[x];
	}
}

二、已知后序中序求先序

第一步,后序遍历最后一个位置肯定是根节点,然后在中序遍历中确定该根结点的位置
第二步,确定好位置后,即可分别对左子树和右子树进行递归
在这里插入图片描述
干代码:

void pre_order(int x, int y, int p, int q) {  //x~y为中序遍历 p~q为后序遍历
	if (x > y || p > q) return;//规定边界条件
	else {
		int root_pos = s1.find(s2[q]);   //利用根左右的特性来在中序队列中查找
		cout << s2[q];
		pre_order(x, root_pos - 1, p, p + root_pos - x - 1);      //递归左子树
		pre_order(root_pos + 1, y, p + root_pos - x, q - 1);      //递归右子树		
	}
}

最后干上完整代码:

#define  _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <stack>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
#include <fstream>
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define LNF = 0x3f3f3f3f3f3f3f3f;
using namespace std;
const int maxn = 100002;
string s1, s2;

void post_order(int x, int y, int p, int q) {  //x~y为前序遍历 p~q为中序遍历
	if (x > y || p > q) return;//规定边界条件
	else {
		int root_pos = s2.find(s1[x]);   //利用根左右的特性来在中序队列中查找
		post_order(x + 1, x + root_pos - p, p, root_pos - 1);      //递归左子树
		post_order(x + root_pos - p + 1, y, root_pos + 1, q);      //递归右子树
		cout << s1[x];
	}
}

void pre_order(int x, int y, int p, int q) {  //x~y为中序遍历 p~q为后序遍历
	if (x > y || p > q) return;//规定边界条件
	else {
		int root_pos = s1.find(s2[q]);   //利用根左右的特性来在中序队列中查找
		cout << s2[q];
		pre_order(x, root_pos - 1, p, p + root_pos - x - 1);      //递归左子树
		pre_order(root_pos + 1, y, p + root_pos - x, q - 1);      //递归右子树		
	}
}

int main() {
	//cin >> s2 >> s1; //把中前遍历当做字符串输入
	//int len = s1.length() - 1;//因为是0开始,所以要减一
	//post_order(0, len, 0, len);//递归求后序遍历

	cin >> s1 >> s2; //把中后遍历当做字符串输入
	int len = s1.length() - 1;//因为是0开始,所以要减一
	pre_order(0, len, 0, len);//递归求前序遍历
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值