Advertisement
nikunjsoni

337

May 7th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     int rob(TreeNode* root) {
  15.         auto p = dfs(root);
  16.         return max(p.first, p.second);
  17.     }
  18.    
  19.     pair<int, int> dfs(TreeNode* root){
  20.         // First -> including current node;
  21.         // Second -> excluding current node / Get max of previous elements sum;
  22.         pair<int, int> sum  = {0, 0};
  23.         if(!root) return sum;
  24.        
  25.         // Dfs on left and right subtree.
  26.         auto left = dfs(root->left);
  27.         auto right = dfs(root->right);
  28.  
  29.         // If current element is included.
  30.         sum.first = root->val + left.second + right.second;
  31.        
  32.         // If current element is excluded, get max of last element.
  33.         sum.second = max(left.first, left.second) + max(right.first, right.second);
  34.         return sum;
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement