UVA 548 - Tree

题目大意:给你二叉树的中序遍历,和后序遍历的结果。让你求,权值最小的叶子节点。也就是从根到叶子结点的值的和最小的点。如果权值相等,输出叶子节点值较小的点。

解题思路:由后序遍历得到根节点的值。即后序遍历最后一个为根,然后在中序遍历中查找这个根的值的位置,左边为左子树,右边为右子树。针对左子树也是同样操作,找“根”(左子树的全体作为树),根的左右子树。也就是递归求树。建树。这是第一题完全自己做得...刚开始以为是求最小叶子节点,后面根据写完的代码,改一下就有了树,所以这里我不会讲思路的。美滋滋。欢迎一起讨论

ac代码:

#include <iostream>
#include <map>
using namespace std;
multimap <int, int>ma;
map <int, int>::iterator it;
int a[10005], b[10005], count;
using namespace std;

struct tree{
	int data;
	int sum;
	tree *left;
	tree *right;
	tree()
	{
		data = sum = 0;
		left = right = NULL;
	}
}; 
tree *ro;
tree* dfs(int m, int n, int t, int k, tree* ro)
{
	int root=b[n];
	tree *node;
	node = new tree;
	node->data = root;
	node->sum = ro->sum + root;	
	if (k-t == 1){
		ma.insert(make_pair(node->sum, node->data));
		return node;
	}
	for (int i=t; i<k; i++)
		if (a[i] == root){
			node->left = dfs(m, m+i-t-1, t, i, node);
			node->right = dfs(m+i-t, n-1, i+1, k, node); 
			break;
		}
}

int input(int a[])
{
	char c = getchar();
	int i = 1;
	while (c != '\n'){
		scanf("%d", &a[i++]);
		c = getchar();
	}
return i;
}
int main()
{
	int i;
	char c;
	while (scanf("%d", &a[0])!=EOF){
		ro = new tree;
		input(a);
		scanf("%d", &b[0]);
		count = input(b);
		dfs(0, count-1, 0, count, ro);
		it=ma.begin();
		cout << it->second << endl;
		ma.clear();
	}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值