华为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)
相关推荐
迷迭香yy7 小时前
行业板块轮动因子实战从板块资金到因子建模的本地化Python全流程
数据库·人工智能·python
W_326007 小时前
Python文件进阶:一维数据与 CSV 文件读写
开发语言·python
Tyler_TXZ7 小时前
C++C语言之——二叉树
c语言·开发语言·数据结构·c++·二叉树
不会代码的小猴8 小时前
C++新增关键字
开发语言·c++·笔记
yaoxin5211238 小时前
497. Java 反射 - 使用反射读取注解
java·开发语言·python
2019一路前行8 小时前
Python 函数式编程
开发语言·python
专注仿真8 小时前
问答大模型技术方案算法实现-RAPTOR树构建算法与BEG集成使用
python·算法
冯汉栩9 小时前
Swift Control View,Label渐变颜色(源码)
开发语言·ios·swift
从小就看凹凸曼^o^10 小时前
Python基础5 - 字典与集合:(1)字典
开发语言·python
Herbert_hwt10 小时前
第七章 Java深入理解枚举类型
java·开发语言·算法