华为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)
相关推荐
2501_944521596 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
行思理6 小时前
go语言学习难度及适合学习的人群
开发语言·学习·golang
wangchunyu1148 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
程序 代码狂人9 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
2501_9445215910 小时前
Immer 跨端三方库仓颉适配全流程
python·eclipse·django
信誓旦旦的程序猿10 小时前
【Python量化实战宝典 #26】止损与回撤控制手册:移动止损、最大回撤(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
2501_9445215910 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
Patrick在香港10 小时前
同一行 strftime,两台机器跑出两种日期
python·datetime·时区·locale·日期处理
2601_9679873710 小时前
用Python+OpenCV+YOLO写个游戏脚本:从自动瞄准到自动采集的保姆级教程
python·opencv·yolo·目标检测·游戏自动化
meiying883810 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化