Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- int rob(TreeNode* root) {
- auto p = dfs(root);
- return max(p.first, p.second);
- }
- pair<int, int> dfs(TreeNode* root){
- // First -> including current node;
- // Second -> excluding current node / Get max of previous elements sum;
- pair<int, int> sum = {0, 0};
- if(!root) return sum;
- // Dfs on left and right subtree.
- auto left = dfs(root->left);
- auto right = dfs(root->right);
- // If current element is included.
- sum.first = root->val + left.second + right.second;
- // If current element is excluded, get max of last element.
- sum.second = max(left.first, left.second) + max(right.first, right.second);
- return sum;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement