跳转至

337. House Robber III

Tags: Medium Tree Depth-first Search

Links: https://leetcode.com/problems/house-robber-iii/


The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "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 forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

解法一:对于某一个节点,如果其左子节点存在,通过递归调用函数,算出不包含左子节点返回的值,同理,如果右子节点存在,算出不包含右子节点返回的值,那么此节点的最大值可能有两种情况,一种是该节点值加上不包含左子节点和右子节点的返回值之和,另一种是左右子节点返回值之和不包含当期节点值,取两者的较大值返回即可,因为存在很多的重复计算,所以用一个哈希表来进行一下优化。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    unordered_map<TreeNode *, int> um;
public:
    int rob(TreeNode* root) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        return DFS(root);
    }

    int DFS(TreeNode *root) {
        if (!root) return 0;
        if (um.find(root) != um.end()) return um[root];

        int res = 0;
        if (root -> left) res += DFS(root -> left -> left) + DFS(root -> left -> right);
        if (root -> right) res += DFS(root -> right -> left) + DFS(root -> right -> right);
        res = max(res + root -> val, DFS(root -> left) + DFS(root -> right));

        return um[root] = res;
    }
};