UVa548 (树 Tree)

1、题目大意

  1. 题目链接UVa 548
  2. 给出一棵带权二叉树的中序遍历和后序遍历,求出根到叶子的路径上权和最小的叶子,如果有多解,该叶子本身的权应尽量小。

2、解题思路

  1. 根据中序遍历序列和后序遍历序列递归建树。
  2. 递归遍历每一个叶子结点,求出权和最小的叶子。

3、参考代码

#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<cctype>
#include<string>
#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())

using namespace std;

int best, best_sum;
struct node {
	int v;
	node *left, *right;
	node() :v(0), left(NULL), right(NULL) {}
};

void to_array(string& s,vector <int>& a){
	for (int i = 0; i < s.size(); i++) {
		int t = 0;
		while (isdigit(s[i]))
			t = 10 * t + s[i] - '0', i++;
		a.push_back(t);
	}
}

node* build_tree(vector <int> in_order, vector <int> post_order) {
	if (in_order.size() == 0 && post_order.size() == 0)
		return NULL;
	else if (in_order.size() == 1 && post_order.size() == 1) {
		node* root = new node();
		root->v = in_order.front();
		return root;
	}
	else {
		int mid = post_order.back();
		auto it = find(ALL(in_order), mid);
		vector <int> a1, a2, b1, b2;
		copy(in_order.begin(), it, INS(a1));
		copy(it + 1, in_order.end(), INS(a2));
		copy(post_order.begin(), post_order.begin() + a1.size(), INS(b1));
		copy(post_order.end() - a2.size() - 1, post_order.end() - 1, INS(b2));
		node* tree = new node();
		tree->v = mid;
		tree->left = build_tree(a1, b1);
		tree->right = build_tree(a2, b2);
		return tree;
	}
}

void cal(node* tree,int sum) {
	if (tree == NULL) return;
	sum += tree->v;
	if (tree->left) cal(tree->left, sum);
	if (tree->right)cal(tree->right, sum);
	if (tree->left == NULL && tree->right == NULL) {
		if (sum < best_sum || (sum == best_sum && best > tree->v)) {
			best_sum = sum;
			best = tree->v;
		}
	}
}

int main() {
	string s1, s2;
	while (getline(cin, s1) && getline(cin, s2)) {
		best = best_sum = 100000000;
		vector <int> a, b;
		to_array(s1, a);
		to_array(s2, b);
		node* tree = build_tree(a, b);
		int sum = 0;
		cal(tree, sum);
		cout << best << endl;
	}
	return 0;
}

4、解题感悟

  1. 还是比较习惯写链式存储结构的二叉树。如果不是完全二叉树,感觉写数组存储方式的二叉树会很麻烦,而且比较容易出错。也可能是我理解得不够深入吧。有空需要练练静态链表。
  2. 第一次写递归建树的算法,是完全根据自己的理解写出来的,还是颇有成就感的。
  3. 最后遍历叶子结点的时候,注意函数参数的选择。另外使用全局变量要格外小心。
  4. 没有在程序中及时释放动态申请的内存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值