UVa 548 Tree 根据后序遍历和中序遍历建树后DFS

9 篇文章 0 订阅




#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#define PAUSE system("pause")
using namespace std;

const int maxv = 10000 + 10;
//lch和rch分别记录当前节点的左右子树的根节点
int in_order[maxv], post_order[maxv], lch[maxv], rch[maxv];
int n, ans, pos;

bool read(int *a) {
	string line;
	if (!getline(cin, line)) return false;
	stringstream ss(line);
	int x;
	n = 0;
	while (ss >> x) a[n++] = x;  //流化输入
	return true;
}

//inorder [L1, R1], postorder [L2, R2]
int build(int L1, int R1, int L2, int R2) {
	if (L1 > R1) return 0; //空树返回0
	int root = post_order[R2];
	int p = L1;
	while (in_order[p] != root) p++; //debug
	int cnt = p - L1; //左子树长度
	lch[root] = build(L1, L1 + cnt - 1, L2, L2 + cnt - 1);
	rch[root] = build(p + 1, R1, L2 + cnt, R2 - 1);
	return root;
}

void dfs(int root, int sum) {
	sum += root;
	if (!lch[root] && !rch[root]) {
		if (sum < ans || (sum == ans && root < pos)) {
			ans = sum;
			pos = root;
		}
		return;
	}
	if (lch[root]) dfs(lch[root], sum); //debug if(lch[root])
	if (rch[root]) dfs(rch[root], sum); //debug if(rch[root])
}

int main()
{
	while (read(in_order)) {
		read(post_order);

		int root = build(0, n - 1, 0, n - 1);

		ans = pos = 0x7fffffff;
		dfs(root, 0);
		printf("%d\n", pos);
	}
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值