class Solution {
public:
int returnBranchValue(int index, int& increases, int n, vector<int>& cost)
{
// the children's indexes
int leftIndex = (index * 2) + 1;
int rightIndex = (index * 2) + 2;
if (leftIndex >= n)
{
return cost[index];
}
// never call returnBranchValue on an index that doesn't exist in cost.
int sumLeft = returnBranchValue(leftIndex, increases, n, cost);
int sumRight = returnBranchValue(rightIndex, increases, n, cost);
int diff = std::abs(sumLeft - sumRight);
int max = std::max(sumLeft, sumRight);
increases += diff;
return max + cost[index];
}
int minIncrements(int n, vector<int>& cost) {
int increases = 0;
// Define branch value of a node as the largest sum of a path from that node to one of its leafs. So would have to travel to each leaf and see what the sum is, then the largest of these paths' sums is the node's branch value.
// As we dfs traverse the tree, for the current node return the current node's value plus the larger of the children's branch values. That's this node's branch value.
// At each node there's a sum from the two children's branches. Say one is a larger sum and the other is a smaller sum.
// The smaller branch's value needs to be increased by the difference between the larger branch and the smaller branch.
// So also increase the increases reference variable.
returnBranchValue(0, increases, n, cost);
return increases;
}
};