1
+ // Runtime: 28 ms, faster than 72.39% of C++ online submissions for House Robber III.
2
+ // Memory Usage: 23.8 MB, less than 23.60% of C++ online submissions for House Robber III.
3
+
4
+ /* *
5
+ * Definition for a binary tree node.
6
+ * struct TreeNode {
7
+ * int val;
8
+ * TreeNode *left;
9
+ * TreeNode *right;
10
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11
+ * };
12
+ */
13
+ typedef unordered_map<TreeNode*, int > HashMap;
14
+ class Solution
15
+ {
16
+ public:
17
+ int rob (TreeNode* root)
18
+ {
19
+ HashMap hashmap;
20
+ return helper (root, hashmap);
21
+ }
22
+ private:
23
+ int helper (TreeNode* root, HashMap& hashmap)
24
+ {
25
+ if (!root)
26
+ return 0 ;
27
+ if (hashmap.find (root) == hashmap.end ())
28
+ {
29
+ int notrobfirst = helper (root->left , hashmap) + helper (root->right , hashmap);
30
+
31
+ int robfirst = root->val ;
32
+ if (root->left && root->right )
33
+ robfirst += helper (root->left ->left , hashmap) +
34
+ helper (root->left ->right , hashmap) +
35
+ helper (root->right ->left , hashmap) +
36
+ helper (root->right ->right , hashmap);
37
+
38
+ else if (root->left )
39
+ robfirst += helper (root->left ->left , hashmap) + helper (root->left ->right , hashmap);
40
+
41
+ else if (root->right )
42
+ robfirst += helper (root->right ->left , hashmap) + helper (root->right ->right , hashmap);
43
+
44
+ hashmap.insert (make_pair (root, max (notrobfirst, robfirst)));
45
+ }
46
+ return hashmap.at (root);
47
+ }
48
+ };
0 commit comments