-
Notifications
You must be signed in to change notification settings - Fork 0
/
337-house-robber-1.cpp
73 lines (57 loc) · 1.41 KB
/
337-house-robber-1.cpp
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
63
64
65
66
67
68
69
70
71
72
73
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stdio.h>
#include <memory.h>
class Solution1 {
public:
int count(TreeNode* root){
if(root == NULL) return 0;
int left_m = 0;
int left_mm = 0;
int right_m = 0;
int right_mm = 0;
TreeNode* l = root->left;
TreeNode* r = root->right;
if(l != NULL){
left_m = count(l);
left_mm = count(l->left) + count(l->right);
}
if(r != NULL){
right_m = count(r);
right_mm = count(r->left) + count(r->right);
}
int m1 = root->val + left_mm + right_mm;
int m2 = left_m + right_m;
return (m1 > m2) ? m1 : m2;
}
int rob(TreeNode* root) {
int r = count(root);
return r;
}
};
class Solution {
public:
array<int , 2> fac(TreeNode * root)
{
if(!root)
{
array<int , 2> p = {0,0};
return p;
}
array<int , 2> l = fac(root->left) , r = fac(root->right) , s;
s[0] = max(l[0] , l[1]) + max(r[0] , r[1]);
s[1] = root->val + l[0] + r[0];
return s;
}
int rob(TreeNode* root) {
array<int , 2> a = fac(root);
return max(a[0] , a[1]);
}
};