Make Costs of Paths Equal in a Binary Tree - DFS [JS]

Description 

Solution: DFS

Key point: For each node, the sum of the all children paths must be equal since they share the same root path.
Since we can only increase node values, we must make all path sums equal to the maximum path sum.
Increase the child node with the smaller path sum to become equal to the larger path sum.
Then, return the maximum out of the left and right path sums.

n = number of nodesh = height of tree
Time Complexity: O(n)
Space Complexity: O(h)

var minIncrements = function(n, cost) {
  let ans = 0;
  dfs(1);
  return ans;
  
  function dfs(i) { 
    if (i * 2 > n) return cost[i - 1]; // leaf node
    let leftSum = dfs(2 * i), rightSum = dfs(2 * i + 1);
    ans += Math.max(leftSum, rightSum) - Math.min(leftSum, rightSum);
    return cost[i - 1] + Math.max(leftSum, rightSum);
  }  
};

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]