/**
* 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) {
// edge case
if(root == NULL) return 0;
// regular case
pair<int, int> result = dp(root);
return max(result.first, result.second);
}
// pair<int, int> --> pair<contain root, not contain root>
pair<int, int> dp(TreeNode* root) {
// stop condition
if(root == NULL) return {0,0};
if(root->left == NULL and root->right == NULL) return {root->val, 0};
// regular condition
pair<int, int> left = dp(root->left);
pair<int, int> right = dp(root->right);
int r = left.second + right.second + root->val;
int n_r = left.first + right.first;
return {max(r, n_r), n_r};
}
};