首页 > 其他 > 详细

UVA548 UVALive5266 Tree【二叉树遍历】

时间:2019-02-24 12:09:15      阅读:151      评论:0      收藏:0      [点我收藏+]

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

Regionals 1997 >> Latin America - Mexico and Central America

问题链接UVA548 UVALive5266 Tree
问题简述:(略)
问题分析
????给定二叉树的中序遍历和后序遍历(整数表示结点),计算从根到叶子结点的路径上的最小权和(表示结点整数的和)。
????先用中序遍历和后序遍历构造二叉树,再用DFS算法遍历二叉树算一下叶子结点的权和,然后求出最小权和。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA548 UVALive5266 Tree */

#include <bits/stdc++.h>

using namespace std;

const int N = 10000;
int in_order[N], post_order[N];
int dcnt;
int lch[N], rch[N];
int idx, minsum;

bool read(int *a)
{
    string line;
    if(!getline(cin, line))
        return false;
    stringstream ss(line);
    dcnt = 0;
    int x;
    while(ss >> x)
        a[dcnt++] = x;

    return dcnt > 0;
}

int buildTree(int l1, int r1, int l2, int r2)
{
    if(l1 > r1)
        return 0;
    int p = l1;
    int root = post_order[r2];
    while(in_order[p] != root)
        p++;
    int cnt = p - l1;
    lch[root] = buildTree(l1, p - 1, l2, l2 + cnt - 1);
    rch[root] = buildTree(p+1, r1, l2 + cnt, r2-1);
    return root;
}

void dfs(int root, int sum)
{
    sum += root;
    if(!lch[root] && !rch[root]) {
        if(sum < minsum || (sum == minsum && root < idx)) {
            minsum = sum;
            idx = root;
        }
    }

    if(lch[root])
        dfs(lch[root], sum);
    if(rch[root])
        dfs(rch[root], sum);
}

int main()
{
    while(read(in_order)) {
        read(post_order);

        int root = buildTree(0, dcnt-1, 0, dcnt-1);

        minsum = INT_MAX;
        idx = root;
        dfs(root, 0);
        printf("%d\n", idx);
    }

    return 0;
}

UVA548 UVALive5266 Tree【二叉树遍历】

原文:https://www.cnblogs.com/tigerisland45/p/10425653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!