337. House Robber III
Medium
165733FavoriteShare
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:
Input: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
#include<iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <math.h>
#include <string>
#include <utility>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
//int dfs(TreeNode* root,bool parent) {
// if (root == NULL)return 0;
// int res = 0;
//
// int left, right;
// int left_t, right_t;
// left = dfs(root->left, false);
// right = dfs(root->right, false);
// if (parent) {
//
// return left + right;
// }
// else {
// left_t = dfs(root->left, true);
// right_t = dfs(root->right, true);
// return max(left_t + right_t + root->val, left + right);
// }
//
//}
std::pair<int,int> dfs(TreeNode* root) {
int with, without;
//int withleft, withoutleft;
auto [withleft, withoutleft] = dfs(root->left);
auto [withright, withoutright] = dfs(root->right);
without = withleft + withright;
with = root->val + withoutleft + withoutright;
with = max(with, without);
return make_pair(with,without);
}
int rob(TreeNode* root) {
auto[with, _] = dfs(root);
return with;
}
};