UVA 548 Tree 中序+后序构造二叉树dfs

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

题目链接:https://vjudge.net/problem/UVA-548

题意

给出二叉树的中序遍历序列和后序遍历序列,以及每个节点的权值,求从叶子节点到根节点权值和最小且最小权值的叶子的权值。

题解

后序遍历序列的最后一个点便是根节点,在中序序列中找到根节点,便可以得到根节点左右子节点的个数,递归求解,可以构造出二叉树。dfs计算从根节点到叶子节点的权值和,求出最小值。
读取一行:getline(cin, line),stringstream是字符串流。

//#include <bits/stdc++.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<stack>
#include<queue>
#include<sstream>
#include<iostream>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;

const int maxn = 10010;
int lf[maxn], rt[maxn], post_order[maxn], in_order[maxn];
int n, best, best_sum;

bool input(int *a){
    n = 0;
    string line;
    if(!getline(cin, line)) return false;
    stringstream ss(line);
    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 = post_order[r2];
    int p = l1;
    while(in_order[p] != root) p++;
    int cnt = p-l1;
    lf[root] = build(l1, p-1, l2, l2+cnt-1);
    rt[root] = build(p+1, r1, l2+cnt, r2-1);
    return root;    //易漏 
}

void dfs(int u, int sum){
    sum += u;
    if(!lf[u] && !rt[u]){
        if(sum<best_sum || sum == best_sum && u<best){
            best = u, best_sum = sum;
        }
    }
    if(lf[u]) dfs(lf[u], sum);
    if(rt[u]) dfs(rt[u], sum);
}

int main(){
    while(input(in_order)){
        input(post_order);
        build(0, n-1, 0, n-1);
        best = INF, best_sum = INF;
        dfs(post_order[n-1], 0);
        printf("%d\n", best);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值