sandeep03edu

Minimum Cost Binary Tree

Jul 20th, 2022
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. int setHeights(int i, vector<int> &heights, vector<int> &cost){
  6.     int n = heights.size();
  7.     if(i>=n){
  8.         return 0;
  9.     }
  10.    
  11.     int leftHeight = 0, rightHeight = 0;
  12.     if(2*i+1<n){
  13.         leftHeight = cost[2*i] + setHeights(2*i+1, heights, cost);
  14.     }
  15.    
  16.     if(2*i+2<n){
  17.         rightHeight = cost[2*i+1] + setHeights(2*i+2, heights, cost);
  18.     }
  19.    
  20.     return heights[i] = max(leftHeight, rightHeight);
  21. }
  22.  
  23. int getAns(int i, vector<int> &heights, vector<int> &cost){
  24.     int n = heights.size();
  25.     if(i>=n){
  26.         return 0;
  27.     }
  28.    
  29.     int leftAns = 0, rightAns=0;
  30.    
  31.     if(2*i+1<n){
  32.         leftAns = heights[i] - heights[2*i+1] - cost[2*i] + getAns(2*i+1, heights, cost);
  33.     }
  34.     if(2*i+2<n){
  35.         rightAns = heights[i] - heights[2*i+2] - cost[2*i+1] + getAns(2*i+2, heights, cost);
  36.     }
  37.    
  38.     return leftAns + rightAns;
  39. }
  40.  
  41. int main() {
  42.     // your code goes here
  43.    
  44.     // Ques Input
  45.     vector<int> cost = {3,1,2,1,5,4};
  46.     int n = 7;
  47.    
  48.    
  49.     // Soln begins
  50.     vector<int> heights(n, 0);
  51.  
  52.     setHeights(0, heights, cost);
  53.    
  54.     int ans = getAns(0, heights, cost);
  55.    
  56.     cout<<ans<<endl;
  57.    
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment