华为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)
相关推荐
是喵斯特ya20 小时前
python开发web暴力破解工具(进阶篇 包含验证码识别和token的处理)
开发语言·python·web安全
长安牧笛20 小时前
职业技能学习路径规划工具,用户输入目标岗位,如AI工程师,结合现有技能水平,推荐分阶段学习资源(课程/书籍/项目),设置学习进度提醒。
python
零K沁雪20 小时前
multipart-parser-c 使用方式
c语言·开发语言
长安牧笛21 小时前
智能衣柜—穿搭助手,内置温湿度传感器,潮湿天气启动除湿功能,防止衣服发霉,APP还能记录衣服穿着频率,推荐久没穿的衣服,避免穿搭重复。
python
free-elcmacom21 小时前
机器学习高阶教程<8>分布式训练三大核心策略拆解
人工智能·分布式·python·机器学习
魔镜前的帅比21 小时前
多工具组合执行链详解
python·ai
chilavert31821 小时前
技术演进中的开发沉思-260 Ajax:核心动画
开发语言·javascript·ajax
云中飞鸿21 小时前
为什么有out参数存在?
开发语言·c#
飞天遇见妞21 小时前
C/C++中宏定义的使用
c语言·开发语言·c++