华为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)
相关推荐
kk”1 天前
C++智能指针
开发语言·c++
MX_93591 天前
以配置非自定义bean来演示bean的实例化方式
java·开发语言·后端
进击的小头1 天前
传递函数与系统特性(核心数学工具)
python·算法·数学建模
小王努力学编程1 天前
LangChain——AI应用开发框架(核心组件2)
linux·服务器·c++·人工智能·python·langchain·信号
2501_944521591 天前
Flutter for OpenHarmony 微动漫App实战:动漫卡片组件实现
android·开发语言·javascript·flutter·ecmascript
高洁011 天前
数字孪生应用于特种设备领域的技术难点
人工智能·python·深度学习·机器学习·知识图谱
Piar1231sdafa1 天前
基于YOLOv26的海洋鱼类识别与检测系统深度学习训练数据集Python实现_1
python·深度学习·yolo
不会代码的小测试1 天前
页面动态元素无法快速复制定位解决
python·selenium·自动化
superman超哥1 天前
派生宏(Derive Macro)的工作原理:编译时元编程的艺术
开发语言·rust·开发工具·编程语言·rust派生宏·derive macro·rust元编程
easyboot1 天前
C#使用pythonnet简单示例
开发语言·python·c#