2673. 使二叉树所有路径值相等的最小代价 【自底向上 + 贪心】

48 阅读1分钟

2673. 使二叉树所有路径值相等的最小代价

class Solution:
    def minIncrements(self, n: int, cost: List[int]) -> int:
        # 计算 所有路径的最大值
        # 优先 增大根路径

        # 从 叶子结点, 向上 依次修改
        res = 0
        for i in range(n - 2, 0, -2):
            res += abs(cost[i] - cost[i + 1])  # 左 右
            cost[i//2] += max(cost[i], cost[i + 1])  # 对应的parent结点 累加

        return res 

image.png

class Solution:
    def minIncrements(self, n: int, cost: List[int]) -> int:
        # 计算 所有路径的最大值
        # 优先 增大根路径

        # 从 叶子结点, 向上 依次修改
        res = 0
        for i in range(n//2, 0, -1):  # 层数
            res += abs(cost[i * 2 - 1] - cost[i * 2])  # 左 右  本来是 2 * i  2 * i + 1  对应 cost数组下标, 要 -1
            cost[i - 1] += max(cost[i * 2 - 1], cost[i * 2])  # 对应的parent结点 累加

        return res 

C++

class Solution {
public:
    int minIncrements(int n, vector<int>& cost) {
        int res = 0;
        for (int i = n / 2; i > 0; --i){// 层数
            res += abs(cost[i * 2 - 1] - cost[i * 2]); // 将 同一parent结点的两个子节点 变成一样的
            cost[i - 1] += max(cost[i * 2 - 1], cost[i * 2]); // 累加到 parent 结点
        }
        return res;
    }
};
class Solution {
public:
    int minIncrements(int n, vector<int>& cost) {
        int res = 0;
        for (int i = n - 2; i > 0; i -= 2){
            res += abs(cost[i] - cost[i + 1]);
            cost[i / 2] += max(cost[i], cost[i + 1]);
        }
        return res;
    }
};