UVA 548 - Tree

题目不难,按照中序和后序递归建树,对于每一个节点,设置cur记录该节点的节点值,设置total记录从根节点到该节点的路径的节点值之和,然后按照层序遍历,边遍历边计算,如果遇到叶子节点,就将计算得到的和与当前记录的最小和进行比较,如果发现计算得到的和更小,那么就对记录进行更新,然后记录遍历到的叶子节点的值。最后输出即可。具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<sstream>
using namespace std;

struct node{
	int cur;
	int total;
	struct node*left;
	struct node*right;
	node(int a){
		cur = a;
		total = 0;
		left = NULL;
		right = NULL;
	}
};

node* construct(vector<int>& inorder,vector<int>& postorder,int in1,int in2,int po1,int po2){
	if (in1 > in2 || po1 > po2) return NULL;
	int i;
	for (i = in1; i <= in2; i++){
		if (inorder[i] == postorder[po2]) break;
	}
	node *root = new node(inorder[i]);
	root->left = construct(inorder,postorder,in1,i-1,po1,po1+(i-1-in1));
	root->right = construct(inorder, postorder, i + 1, in2, po1 + (i - in1), po2-1);
	return root;
}

int main(){
	string s1;
	while (getline(cin,s1)){
		string s2;
		getline(cin, s2);
		vector<int> in;
		vector<int> post;
		stringstream is1(s1);
		stringstream is2(s2);
		int a;
		while (is1 >> a) in.push_back(a);
		while (is2 >> a) post.push_back(a);
		int length = in.size() - 1;
		node* root = construct(in, post, 0, length, 0, length);
		root->total = root->cur;
		int mini = 2147483647;
		int value;
		queue<node*> q;
		q.push(root);
		while (!q.empty()){
			queue<node*> q1;
			while (!q.empty()){
				node* t = q.front();
				q.pop();
				if (t->left == NULL&&t->right == NULL){
					if (t->total < mini){
						mini = t->total;
						value = t->cur;
					}
				}
				if (t->left){
					t->left->total = t->total + t->left->cur;
					q1.push(t->left);
				}
				if (t->right){
					t->right->total = t->total + t->right->cur;
					q1.push(t->right);
				}
			}
			q = q1;
		}
		cout << value << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值