Leetcode 337. House Robber III


原题链接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值