华为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)
相关推荐
一个天蝎座 白勺 程序猿1 天前
Python爬虫(47)Python异步爬虫与K8S弹性伸缩:构建百万级并发数据采集引擎
爬虫·python·kubernetes
XiaoMu_0011 天前
基于Django+Vue3+YOLO的智能气象检测系统
python·yolo·django
honder试试1 天前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky1 天前
JavaScript性能优化实战
开发语言·javascript·性能优化
心本无晴.1 天前
Python进程,线程
python·进程
ponnylv1 天前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人1 天前
第一课、Cocos Creator 3.8 安装与配置
开发语言
Jayden_Ruan1 天前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊1 天前
启动文件Startup_vle.c
c语言·开发语言
VBA63371 天前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言