34. House Robber III
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.Solution: (Using Recursion and Map)
class Solution
{
public:
unordered_map<TreeNode *, int> m;
int rob(TreeNode *root)
{
if (root == NULL)
{
return 0;
}
if (m.find(root) != m.end())
{
return m[root];
}
int val = 0;
if (root->left)
{
val += rob(root->left->left) + rob(root->left->right);
}
if (root->right)
{
val += rob(root->right->left) + rob(root->right->right);
}
int maxVal = max(val + root->val, rob(root->left) + rob(root->right));
m[root] = maxVal;
return maxVal;
}
};Last updated

