华为OD机试真题-传递悄悄话-2023年OD统一考试(C卷)

题目描述:

给定一个二叉树,每个节点上站着一个人,节点数字表示父节点到该节点传递悄悄话需要花费的时间。

初始时,根节点所在位置的人有一个悄悄话想要传递给其他人,求二叉树所有节点上的人都接收到悄悄话花费的时间。

输入描述:

给定二叉树

0 9 20 -1 -1 15 7 -1 -1 -1 -1 3 2

注:-1表示空节点

输出描述:

返回所有节点都接收到悄悄话花费的时间38

补充说明:

示例1

输入:

0 9 20 -1 -1 15 7 -1 -1 -1 -1 3 2

输出:

38

说明:

python 复制代码
from collections import deque

queue = deque()
result = 0

def check(index, nums, father):
    global result
    if index < len(nums) and nums[index] != -1:
        nums[index] += nums[father]
        queue.append(index)
        if nums[index] > result:
            result = nums[index]

if __name__ == "__main__":
    input_str = input()
    tmp2 = input_str.split(" ")
    nums = [int(num) for num in tmp2]

    queue.append(0)
    while queue:
        father = queue.popleft()
        check(2 * father + 1, nums, father)
        check(2 * father + 2, nums, father)

    print(result)
相关推荐
smith成长之旅16 小时前
06 | Mem0 框架分析:为什么要从记忆中提取实体?——Entity Store 的设计动机与工程实现
人工智能·python
smith成长之旅16 小时前
07 | Mem0 框架分析:三路信号融合——语义 + BM25 + Entity Boost 的混合检索
python·算法
笨蛋不要掉眼泪16 小时前
Java并发编程 :深入剖析LinkedBlockingQueue
java·开发语言·网络·并发
不会C语言的男孩16 小时前
C++ Primer Plus 第10章:对象和类
开发语言·c++
不会C语言的男孩16 小时前
C++ Primer Plus 第11章:使用类
开发语言·c++
荣码17 小时前
【Python知识详解】变量与数据类型:深入理解 Python 的数据世界
python
yujunl17 小时前
NetCore常用的中间件说明
开发语言
春日见17 小时前
五分钟入门 强化学习---Q-Learning算法与实现
人工智能·python·深度学习·算法·机器学习·计算机视觉
weixin_4684668517 小时前
Prometheus监控服务部署与实战指南
服务器·后端·python·docker·自动化·prometheus
花酒锄作田17 小时前
[Python]标准库argparse解析命令行参数使用介绍
python