RainX_69

Make Costs of Paths Equal in a Binary Tree | HARD | TRICKY | MUST DO | OA

May 8th, 2023
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | Source Code | 0 0
  1. https://leetcode.com/problems/make-costs-of-paths-equal-in-a-binary-tree/
  2.  
  3. You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1.
  4. Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.
  5. Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.
  6.  
  7. Note:
  8. A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
  9. The cost of a path is the sum of costs of nodes in the path.
  10.  
  11. Example 1:
  12. Input: n = 7, cost = [1,5,2,2,3,3,1]
  13. Output: 6
  14. Explanation: We can do the following increments:
  15. - Increase the cost of node 4 one time.
  16. - Increase the cost of node 3 three times.
  17. - Increase the cost of node 7 two times.
  18. Each path from the root to a leaf will have a total cost of 9.
  19. The total increments we did is 1 + 3 + 2 = 6.
  20. It can be shown that this is the minimum answer we can achieve.
  21.  
  22. Example 2:
  23. Input: n = 3, cost = [5,3,3]
  24. Output: 0
  25. Explanation: The two paths already have equal total costs, so no increments are needed.
  26.  
  27.  
  28. Constraints:
  29. 3 <= n <= 10^5
  30. n + 1 is a power of 2
  31. cost.length == n
  32. 1 <= cost[i] <= 10^4
  33.  
  34. ------------------------------------------------------------------------------------------------------------------------------------
  35.  
  36. class Solution {
  37. public:
  38.     int res=0;
  39.    
  40.     int dfs(vector<int> &cost, int node){
  41.         if(node>cost.size()){
  42.             return 0;
  43.         }
  44.         int L=dfs(cost,2*node);
  45.         int R=dfs(cost,2*node+1);
  46.         res+=abs(L-R);
  47.         return cost[node-1]+max(L,R);
  48.     }
  49.    
  50.     int minIncrements(int n, vector<int>& cost) {
  51.         dfs(cost,1);
  52.         return res;
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment