华为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)
相关推荐
ALex_zry34 分钟前
C++26 std::complex 结构化绑定详解:auto [re, im] = c
c语言·开发语言·c++
如此这般英俊44 分钟前
手搓Claude Code-第六章 subagent
数据结构·人工智能·python·语言模型·自然语言处理
她说..1 小时前
Java 默认值设置方式
java·开发语言·后端·springboot
元Y亨H2 小时前
Python - FastAPI 全方位介绍
python·fastapi
忧郁的紫菜2 小时前
基础实现:单篇 Markdown 转 Word
开发语言·c#·word
甜美的小天鹅2 小时前
Swifter C#之inline还是不inline,这是个问题
开发语言·c#
小短腿的代码世界2 小时前
Qt Bluetooth源码深度解析:从HCI协议到跨平台API的完整架构
开发语言·qt·架构
北冥you鱼2 小时前
Go 语言读取链上数据:从基础到实战
开发语言·后端·golang
nianniannnn2 小时前
c++复习自存--继承
开发语言·c++
error:(3 小时前
【系统与实战双精通】VS Code 调试 ROS2 Python 节点与 Launch 系统指南
android·java·python