-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path337.cpp
More file actions
28 lines (25 loc) · 710 Bytes
/
Copy path337.cpp
File metadata and controls
28 lines (25 loc) · 710 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int rob2(TreeNode *root) {
if (!root) return 0;
int sa = rob2(root->left), sb = rob2(root->right);
int as = root->left ? root->left->val : 0;
int bs = root->right ? root->right->val : 0;
root->val += sa + sb; // max amount with root
return max(sa, as) + max(sb, bs); // max amount without root
}
public:
int rob(TreeNode* root) {
if (!root) return 0;
int r = rob2(root);
return max(r, root->val);
}
};