UVA - 548 C - Tree

题意:输入一个二叉树的中序和后序,输出一个叶子节点,该叶子节点到根的数值总和最小。

分析:先通过后序和中序建立二叉树,在通过DFS进行搜索,找到符合题目要求的叶子节点。中序和后序建立二叉树:使用递归来建立,由后序确定当前递归中的分支的根节点,再在中序中找到根的位置,则中序中根左的为左子树的中序排列,根右的为右子树的中序。设此时左子树的长度为len,则当前的后序的前len个数据是左子树的后序排列。同理进行递归即可。右子树同理。

代码:

#include<stdio.h>
#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
const int maxn=10010;
int inorder[maxn];   //中序遍历数组
int postorder[maxn]; //后序遍历数组
int lch[maxn];        //二叉树左子树
int rch[maxn];         //二叉树右子树
int n;
int best_sum,best;  //最小权值和 最小节点编号
int read_list(int *a)
{
    string line;
    if(!getline(cin,line))
        return 0;
    stringstream ss(line);
    n=0;
    int x;
    while(ss>>x)
        a[n++]=x;
    return n>0;
}
int build(int l1,int r1,int l2,int r2)
{
    if(l1>r1)   //
        return 0;
    int root=postorder[r2];   //根节点
    int p=l1;                 //根节点在中序的位置
    while(inorder[p]!=root)
        p++;
    int cnt=p-l1;
    lch[root]=build(l1,p-1,l2,l2+cnt-1);   //左子树
    rch[root]=build(p+1,r1,l2+cnt,r2-1);   //右子树
    return root;
}

void dfs(int v,int sum)   //dfs搜索
{
    sum+=v;
    if(!lch[v]&&!rch[v])
    {
        if(sum<bestsum||(sum==best_sum&&v<best))
        {
            best=v;
            bestsum=sum;
        }
    }
    if(lch[v])
        dfs(lch[v],sum);
    if(rch[v])
        dfs(rch[v],sum);
}
int main()
{
    while(readlist(in_order))   //读入中序
    {
        readlist(post_order);   //后序
        build(0,n-1,0,n-1);      //建立二叉树
        bestsum=0x3f3f3f3f;
        dfs(postorder[n-1],0); 
        cout<<best<<"\n";
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值