uva 548

15 篇文章 0 订阅

由后续遍历和中序遍历推理出树的结构。使用递归方法做的,有点麻烦,,。注意好在递归过程中参数的设置

#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <string>
#include <string.h>
#include <sstream>

using namespace std;
const int maxn = 10000 + 1000;

int inorder[maxn], postorder[maxn], parent[maxn], temp;
bool isLeaf[maxn];
string str;
int cnt = 0;


bool build_tree(int treeLength, int inStPos, int postStPos, int father)
{
	if (treeLength <= 0)
		return false;

	int nodePos = 0;
	for (int i = inStPos; i < treeLength + inStPos; i++)
	{
		if (postorder[postStPos + treeLength - 1] == inorder[i])
		{
			nodePos = i;
			break;
		}
	}//for
	parent[inorder[nodePos]] = father;

	//左子树
	bool leftson = build_tree(nodePos - inStPos, inStPos, postStPos, inorder[nodePos]);
	
	temp = inorder[nodePos + 1];
	//int rsSt = 0;
	//for (; rsSt < cnt; rsSt++)
	//{
	//	if (postorder[rsSt] == temp)
	//		break;
	//}

	//右子树
	bool rightson = build_tree(treeLength - nodePos - 1 + inStPos, nodePos + 1, postStPos + nodePos - inStPos  , inorder[nodePos]);
	
	isLeaf[inorder[nodePos]] = !(leftson || rightson);
	return true;
}

int main()
{
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
	std::ios::sync_with_stdio(false);
	while (getline(cin, str))
	{
		stringstream ss(str);
		cnt = 0;
		while (ss >> temp)
			inorder[cnt++] = temp;
		for (int i = 0; i < cnt; i++)
			cin >> postorder[i];
		memset(isLeaf, true, sizeof(isLeaf));
		memset(parent, -1, sizeof(parent));
		build_tree(cnt, 0, 0, -1);

		int res = 0, mini = 0;
		bool flag = true;
		for (int i = 0; i < cnt; i++)
		{
			int val = inorder[i];
			if (!isLeaf[val])
				continue;

			int index = val, summ = 0;
			while (index != -1)
			{
				summ += index;
				index = parent[index];
			}

			if (flag || summ < mini)
			{
				flag = false;
				mini = summ;
				res = val;
			}
		}//for
		cout << res << endl;
		cin.get();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值