Advertisement
imashutosh51

Maximum sum of Non-adjacent Nodes

Jul 31st, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. struct Node
  2. {
  3.     int data;
  4.     Node* left;
  5.     Node* right;
  6. };
  7. */
  8. /*
  9. Logic :T.C(O(n)) and S.C O(n)
  10. two case at every node:
  11. case1: select current node,then select grand childrens and because all nodes are positive so add max_sum achieved
  12. from all the grandchildren ie. incl means included
  13.  
  14. case2:don't select current node,so select it's child ie. excl means excluded
  15. finally return the maximum of both.
  16. used map for avoiding same recusion
  17.  
  18.  
  19. */
  20.  
  21. unordered_map<Node*,int> mp;
  22. class Solution{
  23.   public:
  24.     //Function to return the maximum sum of non-adjacent nodes.
  25.     int getMaxSum(Node *root){
  26.         if(!root) return 0;
  27.         if(mp[root]) return mp[root];
  28.        
  29.         int incl=root->data,excl=0;
  30.         if(root->left){
  31.             incl+=getMaxSum(root->left->left);
  32.             incl+=getMaxSum(root->left->right);
  33.         }
  34.         if(root->right){
  35.             incl+=getMaxSum(root->right->left);
  36.             incl+=getMaxSum(root->right->right);
  37.         }
  38.         excl+=getMaxSum(root->left)+getMaxSum(root->right);
  39.         mp[root]=max(incl,excl);
  40.         return mp[root];
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement