Directory link:
Likou Programming Questions-Solution Summary_Sharing + Recording-CSDN Blog
GitHub synchronous question brushing project:
Original title link: LeetCode official website - the technology growth platform loved by geeks around the world
describe:
The thief discovered a new area to steal from. There is only one entrance to this area, which we call it root
.
In root
addition, each house has one and only one "parent" house connected to it. After some reconnaissance, the clever thief realized that "all the houses in this place were arranged like a binary tree." If two directly connected houses are robbed on the same night , the house will automatically call the police.
Given a binary tree root
. Returns the maximum amount a thief can steal without triggering an alarm .
Example 1:
Input: root = [3,2,3,null,3,null,1] Output: 7 Explanation: The maximum amount of money a thief can steal in one night 3 + 3 + 1 = 7
Example 2:
Input: root = [3,4,5,1,3,null,1] Output: 9 Explanation: The maximum amount a thief can steal in one night 4 + 5 = 9
hint:
- The number of nodes in the tree is
[1, 104]
within the range 0 <= Node.val <= 104
Problem-solving ideas:
* Problem-solving ideas:
* The idea of dynamic programming is to find the maximum possible value of each node.
* There are two possibilities for the maximum value of each node, 1: sum of current node + grandchild node, 2: sum of child nodes. The larger one between the two is the possible maximum value of the current node.
Code:
class Solution337
{
public:
int getValue(TreeNode *node)
{
if (node == nullptr)
{
return 0;
}
return node->val;
}
int getMaxValue(TreeNode *root)
{
int sum = root->val;
int childSum = 0;
if (root->left != nullptr)
{
childSum = getMaxValue(root->left);
sum += getValue(root->left->left);
sum += getValue(root->left->right);
}
if (root->right != nullptr)
{
childSum += getMaxValue(root->right);
sum += getValue(root->right->left);
sum += getValue(root->right->right);
}
root->val = max(sum, childSum);
return root->val;
}
int rob(TreeNode *root)
{
getMaxValue(root);
return root->val;
}
};