您的位置:首页 > 编程语言 > C语言/C++

337. House Robber III

2016-07-26 16:50 369 查看

题目:House Robber III

原题链接: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.



给出一个二叉树,求能够得到的最大节点和。

要求:节点不能直接相连。

采用深度优先遍历,统计左子树和右子树分别在加入对应根节点数值和不加入对应根节点数值的情况下的最大和,然后比较。

假设左子树加入根节点和不加入根节点计算的情况下的和分别为robRootL和noRobRootL,右子树在加入根节点和不加入根节点计算的情况下的和分别为,robRootR和noRobRootR。

那么当递归到根节点时:

加入根节点计算的情况下的最大和是:noRobRootL + noRobRootR + root->val

不加入根节点计算的情况下的最大和是:max(robRootL, noRobRootL) + max(robRootR, noRobRootR)

然后再比较两者,取最大值即可。

代码如下:

/**
* 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:
void DFS(TreeNode* root, int& robRoot, int& noRobRoot) {
robRoot = 0, noRobRoot = 0;
if(!root) return;
int robL, robR, noRobL, noRobR;
DFS(root->left, robL, noRobL);
DFS(root->right, robR, noRobR);
robRoot = noRobL + noRobR + root->val;
noRobRoot = max(robL, noRobL) + max(robR, noRobR);
return;
}
int rob(TreeNode* root) {
int robRoot, noRobRoot;
DFS(root, robRoot, noRobRoot);
return max(robRoot, noRobRoot);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++ dfs