class Solution {
private int num;
private int[] tree;
private int res;
public int minIncrements(int n, int[] cost) {
this.num = n;
this.tree = cost;
dfs(0);
return res;
}
// node为当前节点的下标
private int dfs(int node) {
// 如果判断当前节点为叶子节点,返回节点值
if (node * 2 + 1 >= num) {
return tree[node];
}
// 取左子节点路径和
int left = dfs(node * 2 + 1);
// 取右子节点路径和
int right = dfs(node * 2 + 2);
// 计算子节点需要的操作数,累加到res中
res += Math.abs(left - right);
// 返回该节点以下的路径和数值
return Math.max(left, right) + tree[node];
}
}
方法二
class Solution {
public int minIncrements(int n, int[] cost) {
int res = 0;
for (int i = n - 1; i > 0; i -= 2){
// 本节点值
int cur = cost[i];
// 兄弟节点值
int brother = cost[i - 1];
// 拉齐本节点和兄弟节点,累加操作数
res += Math.abs(cur - brother);
// 递归向上更新,父节点向下取整
cost[(i - 1) / 2] += Math.max(cur, brother);
}
return res;
}
}