DS树--二叉树之最大路径

DS树–二叉树之最大路径

题目描述

给定一颗二叉树的逻辑结构(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构

二叉树的每个结点都有一个权值,从根结点到每个叶子结点将形成一条路径,每条路径的权值等于路径上所有结点的权值和。编程求出二叉树的最大路径权值。如下图所示,共有4个叶子即有4条路径,

路径1权值=5 + 4 + 11 + 7 = 27路径2权值=5 + 4 + 11 + 2 = 22

路径3权值=5 + 8 + 13 = 26路径4权值=5 + 8 + 4 + 1 = 18

可计算出最大路径权值是27。

该树输入的先序遍历结果为ABCD00E000FG00H0I00,各结点权值为:

A-5,B-4,C-11,D-7,E-2,F-8,G-13,H-4,I-1
Alt

输入

第一行输入一个整数t,表示有t个测试数据

第二行输入一棵二叉树的先序遍历,每个结点用字母表示

第三行先输入n表示二叉树的结点数量,然后输入每个结点的权值,权值顺序与前面结点输入顺序对应

以此类推输入下一棵二叉树

输出

每行输出每棵二叉树的最大路径权值,如果最大路径权值有重复,只输出1个

输入样例:

2
AB0C00D00
4 5 3 2 6
ABCD00E000FG00H0I00
9 5 4 11 7 2 8 13 4 1

输出样例:

11
27

参考代码:

#include<iostream>
#include<queue>
#include<string>

using namespace std;

struct tree_node {
    char data{};
    int quan{};
    tree_node *left_child{}, *right_child{}, *parent = nullptr;
};

queue<int> q;
queue<tree_node *> leaf;
string str;
int pos = 0;

void create(tree_node *&node) {
    char data = str[pos++];
    if (data == '0')
        node = nullptr;
    else {
        node = new tree_node;
        node->data = data;
        node->quan = q.front();
        q.pop();
        create(node->left_child);
        if (node->left_child != nullptr)
            node->left_child->parent = node;

        create(node->right_child);
        if (node->right_child != nullptr)
            node->right_child->parent = node;

        if (node->left_child == nullptr && node->right_child == nullptr)
            leaf.push(node);
    }
}

int max_long(tree_node *&root) {
    int max = 0;
    while (!leaf.empty()) {
        int all = 0;
        tree_node *node = leaf.front();
        leaf.pop();
        while (node) {
            all += node->quan;
            node = node->parent;
        }
        if (all > max)
            max = all;
    }

    return max;
}

int main() {
    int t;
    cin >> t;
    tree_node *root;
    while (t--) {
        cin >> str;
        pos = 0;
        int n;
        cin >> n;
        while (n--) {
            int k;
            cin >> k;
            q.push(k);
        }

        create(root);
        cout << max_long(root) << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鷸鰥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值