[LeetCode] House Robber III

337. House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

  • new solution update 2022.03.08
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
/**
* 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 {
pair<int,int> helper(TreeNode* node) {
if(!node) return {0,0};
auto [lrob, lpass] = helper(node->left);
auto [rrob, rpass] = helper(node->right);

return {lpass + rpass, max(lrob + rrob + node->val, lpass + rpass)};
}
public:
int rob(TreeNode* root) {
auto [res1, res2] = helper(root);
return max(res1, res2);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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 {
unordered_map<TreeNode*, int> dp[2];
public:
int rob(TreeNode* node, bool canRob = true) {
if(!node) return 0;
if(dp[canRob].count(node)) return dp[canRob][node];
int &res = dp[canRob][node] = rob(node->left, true) + rob(node->right, true);;
if(canRob) res = max(res, node->val + rob(node->left, false) + rob(node->right, false));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/house-robber-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.