码迷,mamicode.com
首页 > 其他好文 > 详细

紫书p155 用中序后序构造二叉树

时间:2017-06-01 00:25:09      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:bsp   dfs   out   位置   最短路径   bit   最短路   main   int   

二叉树各节点权值是不相同的正整数,输入二叉树的中序后序,求到根节点权和最小的叶节点

紫书贼强,递归写的服气,慢慢理解吧

原文是建树之后用dfs搜的,我试着一边建树一边归纳最短路径

#include<bits/stdc++.h>
using namespace std;
const int maxv = 10010;
int in[maxv], post[maxv], lch[maxv], rch[maxv];//中序,后序,左子树,右子树
int n, minnum, minsum;

bool read(int* a)//读一行
{
    string line;
    if(!getline(cin, line))
        return false;
    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, int sum)
{
    if(L1 > R1)//空树
        return 0;
    int root = post[R2];//后序最后一个是根
    int p = L1;
    while(in[p] != root)
        p++;//根在中序的位置
    int cnt = p-L1;//左子树节点数
    lch[root] = build(L1, p-1, L2, L2+cnt-1, sum+root);//
    rch[root] = build(p+1, R1, L2+cnt, R2-1, sum+root);
    if(lch[root] ==0 && rch[root] == 0)//树叶节点
    {
        sum += root;//把叶节点加上
        if(sum <= minsum)
        {
            minsum = sum;
            minnum = root;
        }
    }
    return root;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    while(read(in))
    {
        read(post);
        minsum = 1e9;
        build(0, n-1, 0, n-1, 0);
        cout << minnum << endl;
    }
    return 0;
}

 

紫书p155 用中序后序构造二叉树

标签:bsp   dfs   out   位置   最短路径   bit   最短路   main   int   

原文地址:http://www.cnblogs.com/DearDongchen/p/6926397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!