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.

示例:

     3
    / \
   2   3
    \   \ 
     3   1
Maximum amount of money the thief can rob =  3  +  3  +  1  =  7 .


     3
    / \
   4   5
  / \   \ 
 1   3   1
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 {
public:
    int rob(TreeNode* root)
	{
		pair res = dfs(root);
		return max(res.first, res.second);
	}

private:
	pair dfs(TreeNode* root)
	{
		if (root == nullptr) return pair(0, 0);
		pair res1 = dfs(root->left);
		pair res2 = dfs(root->right);
		pair res;
		res.first = root->val + res1.second + res2.second;
		res.second = max(res1.first, res1.second) + max(res2.first, res2.second);
		return res;
	}
};


你可能感兴趣的:(House Robber III 问题及解法)