2673. Make Costs of Paths Equal in a Binary Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int minIncrements(int n, int[] cost) {
// * 0
// * * 1 2
// * * * 3 4 5 6

int minIncrements = 0;

// 倒序遍历非叶子节点
for (int i = cost.length / 2 - 1; i >= 0; i--) {
minIncrements += Math.abs(cost[i * 2 + 1] - cost[i * 2 + 2]); // 将较小的子节点的值增大
cost[i] += Math.max(cost[i * 2 + 1], cost[i * 2 + 2]); // 将较大的子节点的值累加至父节点,以使更上一层时只需参考下一层的节点值
}

return minIncrements;
}
}

References

2673. Make Costs of Paths Equal in a Binary Tree