UVa548 - Tree

本文介绍了一种使用中序遍历和后序遍历构建二叉树的方法,并通过先序遍历实现了路径求和功能,目的是寻找树中所有路径中节点值之和最小的一条路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:点击打开链接

In the case of multiple paths of least value you should pick the one with the least value on the terminal node.

这个地方真是古怪,被注释起来的代码错了,改成下面就好了,略蛋疼!

C++代码:

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
vector<int> inOrder,postOrder;
int maxNum,x,sum;
struct TreeNode
{
	int data;
	TreeNode *left,*right;
};
TreeNode *build(int inBegin,int inEnd,int postBegin,int postEnd)
{
	if(inBegin<=inEnd&&postBegin<=postEnd)
	{
		vector<int>::iterator itr=find(inOrder.begin()+inBegin,inOrder.begin()+inEnd+1,postOrder[postEnd]);
		int dis=itr-inOrder.begin();
		TreeNode *p=new TreeNode;
		p->data=*itr;
		p->left=build(inBegin,dis-1,postBegin,postBegin+dis-1-inBegin);
		p->right=build(dis+1,inEnd,postBegin+dis-inBegin,postEnd-1);
		return p;
	}
	else
		return NULL;
}
void preOrderTra(TreeNode *head)
{
	if(head)
	{
		sum+=head->data;
		if(head->left==NULL&&head->right==NULL)
		{
			/*if(sum<=maxNum)
			{
				maxNum=sum;
				if(x>head->data)
					x=head->data;
			}*/
			if(sum<maxNum)
			{
				maxNum=sum;
				x=head->data;
			}
		}
		preOrderTra(head->left);
		preOrderTra(head->right);
		sum-=head->data;
	}
}
int main()
{
	string s1,s2;
	while(getline(cin,s1))
	{
		maxNum=numeric_limits<int>::max();
		x=maxNum;
		sum=0;
		getline(cin,s2);
		inOrder.clear();
		postOrder.clear();
		istringstream input1(s1);
		int data;
		while(input1>>data)
			inOrder.push_back(data);
		istringstream input2(s2);
		while(input2>>data)
			postOrder.push_back(data);
		TreeNode *head=build(0,inOrder.size()-1,0,postOrder.size()-1);
		preOrderTra(head);
		cout<<x<<endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值