华为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)
相关推荐
吃我一窝jio8 小时前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw8 小时前
C++ union 的一种妙用法
开发语言·c++
zwd20059 小时前
Manim 怎么放大画面的某一部分?
python·动画·可视化·manim·数学动画
屿华AI9 小时前
AUTOSAR 实战-诊断工具 | UDS 0x27 安全访问的配置化实现:种子密钥算法插件化设计
python·测试工具·汽车
RobinDevNotes9 小时前
Claude Code 剪视频,不上传、不要 API Key
人工智能·python·音视频·开发工具·ipython
starzy199010 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
如夏倾城11 小时前
VRRP(虚拟路由器冗余协议Virtual Router Redundancy Protocol)
网络·python·网络协议·安全·智能路由器·负载均衡·信息与通信
IvanCodes11 小时前
LangChain(04):Runnable 与 LCEL 的执行与组合机制
python·langchain·agent
特创数字科技11 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
布莱克60512 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环