华为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)
相关推荐
用户83562907805114 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng816 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi17 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee17 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay17 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤17 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean18 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽19 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户606487671889620 小时前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api
只与明月听20 小时前
RAG深入学习之Chunk
前端·人工智能·python