Luogu P1030 求先序排列

本文介绍了一种算法,该算法可以根据给定的中序遍历和后序遍历序列来构建并输出对应的先序遍历序列。通过递归地找到根节点,并划分左右子树,最终实现二叉树遍历之间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出中序遍历和后序遍历,求先序遍历

InOrder是左根右, PostOrder是左右根,那么区间内后序遍历的最后一个元素就是根节点了,压入PreOrder,然后查找该值在InOrder中的位置,便能分开左右子树, 进行递归处理,直到没有元素或元素数为1

#include <iostream>
#include <cstdio>
#include <string>

std::string pre, in, post;

void read_data(void);
void calc(const int li, const int ri, const int lp, const int rp);

int main() {
	read_data();
	calc(0, in.size()-1, 0, post.size()-1);
	std::cout << pre;
	//system("pause");
	return 0;
}

void read_data(void) {
	std::cin >> in >> post;
}
// call itself until the num of the element of the subtree equals 1, then push it in, or equals 0, skip
void calc(const int li, const int ri, const int lp, const int rp) { 
	char rootVal = post[rp];
	int midPos = in.find(rootVal);
// root
	pre += rootVal;    
// left subtree
	if (midPos == li+1)    
		pre += in[li];    
	else if (midPos != li)
		calc(li, midPos-1, lp, lp+midPos-1-li);
// right subtree
	if (midPos == ri-1)
		pre += in[ri];
	else if (midPos != ri)
		calc(midPos+1, ri, rp-(ri-midPos), rp-1);

	return;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值