uva 548 tree 树

原题:
You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.

Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.

Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.

Sample Input

3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255

Sample Output

1
3
255
题目大意:
给你一颗树的中序遍历和后序遍历,让你得出一条从根节点到叶子节点一条数值的和最小的路径的叶子节点的值是多少。

#include<iostream>
#include<algorithm>
#include<map>
#include<string>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<vector>
#include<cmath>

using namespace std;
const int maxint=999999;
const int node=100005;
int s1[node],s2[node],s[node];
int l,ans,Max;
//vector<int> vc;

void build(int n,int* s1,int* s2,int sum)//
{
    if(n<=0)
    return ;
    int p=find(s1,s1+n,s2[n-1])-s1;

    sum+=s1[p];

//  vc.push_back(s1[p]);//得到的线序遍历
    if(p<=0&&n-p-1<=0)//走到叶子节点的时候
    {
        if(Max==sum)
        ans=min(ans,s1[p]);
        else
        {
            if(sum<Max)
            {
                Max=sum;
                ans=s1[p];
            }
        }
        return ;
    }

    build(p,s1,s2,sum);

    build(n-p-1,s1+p+1,s2+p,sum);

}

int main()
{
    ios::sync_with_stdio(false);
    string str;
    while(getline(cin,str))
    {
        stringstream in(str);
        int i=0,j=0;
        int num;
        while(in>>num)
        s1[i++]=num;
        getline(cin,str);
        stringstream in1(str);
        while(in1>>num)
        s2[j++]=num;
        ans=Max=maxint;
        build(i,s1,s2,0);
        cout<<ans<<endl;
    }
    return 0;
}




思路:
我真晕了,题刚开始让我读错了。以为是找到和最小那个路径当中,在那个路径里面最小的那个节点。由于对递归算法设计的理解不够,代码没写出来。后来看别人题解发现看不明白,然后又去看题,发现自己题读错了。明白了题意以后,难度就降低了一个档次(可以考虑一下按读错的那个题是怎么写代码的)
当年看过刘汝佳那本白书上有二叉树建树的代码,敲了一遍。根据中序遍历和后序遍历找到先序遍历,在找的同时递归的每次求解最小路径和,当走到叶子节点的时候判断叶子节点的值就好了,虽然题目比较简单,但是此题不错哦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值