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
/
13 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
Credits:
Special thanks to @dietpepsi for
adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路,dfs。递归函数返回两个值,分别是窃取root节点和不窃取root节点时窃取的资金总额。当根节点为空时,直接返回(0,0).根节点不为空的时候,窃取根节点的时候,窃取的资金为left.second+right.second+root->val(此时,不能窃取根节点左右子结点).而不窃取根节点的时候,窃取的资金为max(left.first,left.second)+max(right.first,right.second),即左右子节点能够窃取的最大值之和。
最终,在实际调用完成之后,我们返回窃取root节点和不窃取root节点偷得的资金的最大值。
/** * 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 { pair<int,int> help(TreeNode *root){ if(!root){ return make_pair(0,0); } auto left = help(root->left); auto right = help(root->right); //窃取root节点 int rob_root = left.second+right.second +root->val; //不窃取root节点 int not_rob_root = max(left.first,left.second)+max(right.first,right.second); return make_pair(rob_root,not_rob_root); } public: int rob(TreeNode* root) { auto result =help(root); return max(result.first,result.second); } };