337. House Robber III

来源:互联网 发布:淘宝怎么买二手东西 编辑:程序博客网 时间:2024/05/21 14:59

题目: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);    }};
0 0