337. 打家劫舍 III
为保证权益,题目请参考 337. 打家劫舍 III(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
struct Res {
int val1;
int val2;
Res(int val1, int val2) : val1(val1), val2(val2) {}
int max(){
return ::max(val1, val2);
}
};
class Solution {
public:
int rob(TreeNode *root) {
Res resRes = helper(root);
return max(resRes.val1, resRes.val2);
}
Res helper(TreeNode *root) {
if (root) {
Res resLeft = helper(root->left);
Res resRight = helper(root->right);
return {
root->val + resLeft.val2 + resRight.val2,
resLeft.max() + resRight.max()
};
} else {
return {0, 0};
}
}
};
int main() {
auto * root1 = new TreeNode(4);
auto * root2 = new TreeNode(1);
auto * root3 = new TreeNode(2);
auto * root4 = new TreeNode(3);
root1->left = root2;
root2->left = root3;
root3->left = root4;
Solution so;
cout << so.rob(root1) << endl;
return 0;
}
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62