数据结构 _ PAT练习 _ 1086 Tree Traversals Again

1086 Tree Traversals Again

题目详情

原题链接1

解题思路

在这里插入图片描述
上中下分别是:前序-中序-后序遍历。题目给定了前序-中序,可以求得原二叉树,从而求出后序遍历。

代码

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>

using namespace std;

int main()
{
	typedef vector<int> ints;

	

	stack<ints> med, fore;
	stack<int> back;
	
	size_t N; // numbers
	cin >> N;
	ints rawFore, rawMed;
	while (rawMed.size() != N)
	{
		string tmp;
		cin >> tmp;
		if (tmp.size()==3)
		{
			//Pop
			auto num = back.top();
			back.pop();
			rawMed.push_back(num);
		}
		else
		{
			auto num = 0;
			cin >> num;
			rawFore.push_back(num);
			back.push(num);
		}
	}

	med.push(rawMed);
	fore.push(rawFore);

	while (!med.empty())
	{
		auto subMed = med.top();
		med.pop();
		auto subFore = fore.top();
		fore.pop();
		if (subMed.empty())
			continue;

		const auto root = subFore.front();
		back.push(root);

		const auto iter = find(subMed.begin(), subMed.end(), root);
		const size_t leftLen = iter - subMed.begin();
		const auto rightLen = subMed.size() - leftLen - 1;
		// push the medium order right
		auto medRight = ints(subMed.begin() + 1 + leftLen, subMed.end());
		// push the medium order left
		auto medLeft = ints(subMed.begin(), subMed.begin() + leftLen);
		// push the forward order right
		auto foreRight = ints(subFore.begin() + 1 + leftLen, subFore.end());
		// push the forward order left
		auto foreLeft = ints(subFore.begin() + 1, subFore.begin() + 1 + leftLen);

		if (!medLeft.empty())
		{
			med.push(medLeft);
			fore.push(foreLeft);
		}
		if (!medRight.empty())
		{
			fore.push(foreRight);
			med.push(medRight);
		}
	}

	// print out the ints
	while (!back.empty())
	{
		if (back.size()!=1)
			cout << back.top() << " ";
		else
			cout << back.top() << endl;

		back.pop();
	}

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值