Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2673. Make Costs of Paths Equal in a Binary Tree #254

Open
Woodyiiiiiii opened this issue May 12, 2023 · 0 comments
Open

Leetcode 2673. Make Costs of Paths Equal in a Binary Tree #254

Woodyiiiiiii opened this issue May 12, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

2673. Make Costs of Paths Equal in a Binary Tree

2673. Make Costs of Paths Equal in a Binary Tree

这道题一看就知道是从下至上,归并贪心,树上DFS(不算树上DP)

我在竞赛中用了比较长的思考时间,先算出最大路径,然后用尽量把两颗子树差值往上递增的思想,最后写了很长一段。

那么简单做法是原地修改节点值,然后用全局变量计算子树差值。原地修改成最大值,目的是贪心的思想,暗含了上一段的想法。

class Solution {
    public int minIncrements(int n, int[] cost) {
        int ans = 0;
        for (int i = n / 2 - 1; i >= 0; i--) {
            ans += Math.abs(cost[2 * i + 1] - cost[2 * i + 2]);
            cost[i] += Math.max(cost[2 * i + 1], cost[2 * i + 2]);
        }
        return ans;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant