华为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
而悄悄话的传递,其实父节点将自身得到消息的时延累加到其各个子节点上,最终叶子节点中最大的时延值就是:二叉树所有节点上的人都接收到悄悄话花费的时间
参考代码
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] nodeDelays = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.toArray();
// 记录题解
int maxDelay = 0;
// 根节点的索引是0
LinkedList<Integer> queue = new LinkedList<>();
queue.addLast(0);
while (!queue.isEmpty()) {
int currentNode = queue.removeFirst(); // 当前节点索引
int leftChildIndex = 2 * currentNode + 1; // 左子节点索引
int rightChildIndex = 2 * currentNode + 2; // 右子节点索引
// 当前节点是否存在左子节点
boolean hasLeftChild = leftChildIndex < nodeDelays.length && nodeDelays[leftChildIndex] != -1;
// 当前节点是否存在右子节点
boolean hasRightChild = rightChildIndex < nodeDelays.length && nodeDelays[rightChildIndex] != -1;
// 如果存在左子节点
if (hasLeftChild) {
nodeDelays[leftChildIndex] += nodeDelays[currentNode];
queue.addLast(leftChildIndex);
}
// 如果存在右子节点
if (hasRightChild) {
nodeDelays[rightChildIndex] += nodeDelays[currentNode];
queue.addLast(rightChildIndex);
}
// 当前节点是叶子节点
if (!hasLeftChild && !hasRightChild) {
// 保留叶子节点中最大时延
maxDelay = Math.max(maxDelay, nodeDelays[currentNode]);
}
}
System.out.println(maxDelay);
}
}