uva 548 Tree

链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=489

好吧,这道题让我对二叉树已经基本熟悉了。通过给出的中序遍历和后序遍历来建立二叉树然后找到路径权值最小的叶。

如果存在路径权值相同的叶取叶权值最小的。

(给出前序遍历和中序遍历或者给出中序遍历和后续遍历都能建立一棵树,但是如果给出了前序遍历和后序遍历不能建立一棵确定的树,即存在多种建树的可能)

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<ctype.h>
#include<algorithm>
#include<string>
#define PI acos(-1.0)
#define maxn 100005
#define INF 1<<25
#define MAX 0x7fffffff
typedef long long ll;
using namespace std;
int ans=maxn;
int ii=0;
int pos=0;
int rec=0;
int Build(int *s1,int *s2,int zl,int zr,int hl,int hr)
{
    int n=zr-zl+1;
    int p;
    if(n<=0)
    return 0;
    if(n==1)
    {
        if(rec+s2[hr]<ans)
        {
            ans=rec+s2[hr];
            pos=s2[hr];
        }
        else if(rec+s2[hr]==ans)
        {
            if(pos>s2[hr])
                pos=s2[hr];
        }
        return 0;
    }
    rec+=s2[hr];
    for(int i=zl; i<=zr; i++)
    {
        if(s2[hr]==s1[i])
            p=i;
    }
    Build(s1,s2,zl,p-1,hl,hl+p-zl-1);
    Build(s1,s2,p+1,zr,hr-(zr-p),hr-1);
    rec-=s2[hr];
}
int main()
{
    int s1[maxn];
    int s2[maxn];
    char s;
    while(scanf("%d%c",&s1[ii++],&s)!=EOF)
    {
        ans=maxn;
        if(s!='\n')
        {
            while(scanf("%d%c",&s1[ii++],&s))
            {
                if(s=='\n')
                    break;
            }
        }
        for(int i=0; i<ii; i++)
            scanf("%d",&s2[i]);
        Build(s1,s2,0,ii-1,0,ii-1);
        printf("%d\n",pos);
        ii=0;
        ans=maxn;
        pos=-1;
        rec=0;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值