Leetcode 337. House Robber III

来源:互联网 发布:知乎关注人数最多的 编辑:程序博客网 时间:2024/05/18 00:39

原题链接:https://leetcode.com/problems/house-robber-iii/description/

描述:

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:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.


Solution:

本题是典型的二叉树求和问题,只需分析出所有需要比较的情况即可,对于父节点选中的时候,子节点都不可用,那么就是父节点加上子节点不包含自身的最大值之和,如果父节点不被选中,那么就是所有子节点包含与不包含自身两种情况的最大值之和。

#include <iostream>#include <vector>#include <map>using namespace std;struct TreeNode {    int val;    TreeNode* left;    TreeNode* right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};void InsertTree(TreeNode*& tree) {    int v;    cin >> v;    if (v == 0) {        tree = NULL;        return;    } else {        tree = new TreeNode(v);        InsertTree(tree->left);        InsertTree(tree->right);    }}void DeleteTree(TreeNode*& tree) {    if (tree == NULL) return;    DeleteTree(tree->left);    DeleteTree(tree->right);    delete tree;}pair<int, int> CalRob(TreeNode* tree) {    if (tree == NULL) return pair<int, int>(0, 0);    pair<int, int> left = CalRob(tree->left);    pair<int, int> right = CalRob(tree->right);    int l = left.second + right.second + tree->val;    int r1 = left.first > left.second ? left.first : left.second;    int r2 = right.first > right.second ? right.first : right.second;    int r = r1 + r2;    return pair<int, int>(l, r);}int rob(TreeNode* root) {    pair<int, int> res = CalRob(root);    return res.first > res.second ? res.first : res.second;}int main() {    TreeNode* tree = NULL;    InsertTree(tree);    cout << "Maximum amount of money the thief can rob is: " << rob(tree) << endl;    DeleteTree(tree);    system("pause");    return 0;}
原创粉丝点击