OD C卷 - 传递悄悄话

传递悄悄话 (100)

  • 给定一个二叉树,节点采用顺序存储,如 i=0 表示根节点,2i + 1 表示左子树根,2i + 2 表示右子树根;
  • 每个节点站一个人,节点数值表示由父节点到该节点传递消息需要的时间;
  • 输出从根节点,将消息传递给所有的人需消耗的时间;
    输入描述:
    0 9 20 -1 -1 15 17 -1 -1 -1 -1 3 2 ;节点的顺序存储;-1表示空节点
    输出描述:
    所有的人都收到消息所消耗的时间 38

示例1
输入:
0 9 20 -1 -1 15 17 -1 -1 -1 -1 3 2
输出:
38

示例2
输入:
0
输出:
0

示例3
输入:
0 9
输出:
9

说明:
还原出二叉树如下
在这里插入图片描述

思路:

  • 函数递归

total_time = 0


def get_time(root):
    global total_time, n, alist
    if 2*root+1 < n and 2*root+2< n and alist[2*root+1] == -1 and alist[2*root+2] == -1:
        return alist[root]
    elif 2*root+1 >=n and 2*root+2 >=n:
        return alist[root]

    if 2*root+1 <n and alist[2*root+1] != -1:
        total_time = max(total_time, alist[root] + get_time(2*root+1))

    if 2*root+2 < n and alist[2*root+2] != -1:
        total_time = max(total_time, alist[root] + get_time(2*root+2))

    return total_time


alist = list(map(int, input().strip().split()))
n = len(alist)
get_time(0)

print(total_time)

 

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laufing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值