数据结构算法——1068. 最小权值路径

这篇博客介绍了如何根据中序和后序遍历数组构建二叉树,并找到从根节点到叶子节点的最小路径。通过递归算法实现树的创建,然后遍历寻找最小路径,代码使用C++编写。

题目

在这里插入图片描述
输入1
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5

输入2
3 2 1 4 5 7 6
3 1 2 5 6 7 4

思路

和前面的还原二叉树一样
然后遍历第一个符合的路径即可

代码

#include<iostream>
#include<stack>
#include<sstream>
using namespace std;

int min_road = 9999999;
int min_leaf = 9999999;

struct dot
{
    int data = -1;
    dot* lchild = NULL;
    dot* rchild = NULL;
    
    void med_print()
    {
        if(!this)
            return;
        else
        {
            this->lchild->med_print();
            cout << this->data << " ";
            this->rchild->med_print();
        }
    }
    
};

void create_tree(dot* &root, int* med, int* post, int n)
{
    if(n == 0)
        root = NULL;
    else
    {
        int root_loc = 0;
        while(post[n - 1] != med[root_loc])
            root_loc++;
        root = new dot;
        root->data = med[root_loc];

        create_tree(root->lchild, med, post, root_loc);
        create_tree(root->rchild, med + root_loc + 1, post + root_loc, n - root_loc - 1);
        
    }
}
void min(dot*& root, int road = 0, int leaf = 0)
    {
       
        if(road > min_road)
        {
            return;
        }
        else if(!root)
        {
            if(road < min_road)
            {
                min_road = road;
                min_leaf = leaf;
            }    
            else if(road == min_road)
            {
                if(leaf < min_leaf)
                    min_leaf = leaf;
            }
        }
        else
        {
            if(!root->lchild && !root->rchild)
            {   
                min(root->lchild,road + root->data, root->data);
            }
            if(root->lchild)
                min(root->lchild,road + root->data, root->data);
            if(root->rchild)
                min(root->rchild,road + root->data, root->data);
            
        }
    }
int main()
{
    string str;
    getline(cin,str);

    stringstream sin(str);

    int med[10000] = {0};
    int post[10000] = {0};
    int n = 0;
    while(sin >> med[n++]){}
    getline(cin,str);

    sin.clear();
    sin.str(str);
    n = 0;
    while(sin >> post[n++]){}
    n--;

    // for(int i = 0; i < n ; i++)
    //     cout << med[i] <<" " << post[i] << endl;
    
    dot* root; create_tree(root, med, post, n);
    min(root);
    cout << min_leaf << endl;
}   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值