Skip to content

337.house robber iii

Problem Statement

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.

Approach

Just pass whether we are allowed to pick or not Pick to the children and work accordingly.

/**
 * 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 {
public:
    int f(TreeNode* root, bool pickCurrent, unordered_map<TreeNode*,int>& dp){
        if(!root)
            return 0;
        if(!pickCurrent)
            return f(root->left,true,  dp) + f(root->right,true,  dp);
        if(dp[root])
            return dp[root];
        int pick = root->val + f(root->left,false,  dp) + f(root->right,false,  dp);
        int notPick = f(root->left,true,  dp) + f(root->right,true,  dp);

        return dp[root] = max(pick,notPick);
    }

    int rob(TreeNode* root) {
        unordered_map<TreeNode*,int> dp;
        return f(root,true, dp);    
    }
};