华为OD机试(C卷+D卷)2024真题目录(Java & c++ & python)
题目描述
给定一个二叉树,每个节点上站一个人,节点数字表示父节点到该节点传递悄悄话需要花费的时间。
初始时,根节点所在位置的人有一个悄悄话想要传递给其他人,求二叉树所有节点上的人都接收到悄悄话花费的时间。
输入描述
给定二叉树
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
解题思路
层序遍历序列中,父子节点存在如下关系:
如果父节点在序列中的索引是k,则其两个子节点在序列中的索引分别为 2k+1, 2k+2
而悄悄话的传递,其实父节点将自身得到消息的时延累加到其各个子节点上,最终叶子节点中最大的时延值就是:二叉树所有节点上的人都接收到悄悄话花费的时间
参考代码
# 输入获取
delays = list(map(int, input().split()))
# 记录题解
max_delay = 0
# 根节点的索引是0
queue = [0]
while len(queue) > 0:
parent_index = queue.pop(0) # 父节点索引
left_child_index = 2 * parent_index + 1 # 左子节点索引
right_child_index = 2 * parent_index + 2 # 右子节点索引
# 父节点是否存在左子节点
left_child_exists = left_child_index < len(delays) and delays[left_child_index] != -1
# 父节点是否存在右子节点
right_child_exists = right_child_index < len(delays) and delays[right_child_index] != -1
# 如果存在左子节点
if left_child_exists:
delays[left_child_index] += delays[parent_index]
queue.append(left_child_index)
# 如果存在右子节点
if right_child_exists:
delays[right_child_index] += delays[parent_index]
queue.append(right_child_index)
# 如果是叶子节点
if not left_child_exists and not right_child_exists:
# 保留叶子节点中最大时延
max_delay = max(max_delay, delays[parent_index])
print(max_delay)