leetcode 337 robberies III

Steal the most money!

Title:
After the completion of the last lap after robbing a street and house, discovered a thief can steal new areas. The region has only one entrance, which we call the "root." In addition to the "root", and only the houses a "parent" house associated therewith. After some reconnaissance, clever thief realized that "this place all the houses are arranged similar to a binary tree." If both houses are directly connected robbed the same night, the house alarm.
Calculated without touching the alarm, a thief can steal the maximum amount of night.

示例 1:

输入: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

输出: 7 
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.

示例 2:

输入: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.

Topic analysis

  • Claim
  1. Not rob the house together ⇒ node can not have a direct connection edges
  2. The more houses as robbery ⇒ node and the bigger the better
  • Analysis
    for one node: directly connected to the right node == left node +

If the value of the right node value +> left node of the current node value
to abandon the current node node robbed left and right node
otherwise rob children of the current node node node node and the right and left of
recursion! !

Photo painting is intuitive easy to understand

  • For node 1 == two options (the amount of election who who):
  1. Robbery 1,4,5,6,7
  2. 2,3 robbery
    Here Insert Picture Description

Problem-solving ideas

variable effect
find() Looking function can rob the maximum amount of

process

If the node is a leaf ==> node value returned directly

max( (The maximum amount the maximum amount of left + right node node) , children (current value + node node left child node and the maximum amount + node node maximum amount) ) ==> recursive

Returns the maximum value

code show as below

int find(TreeNode*root)
{
    if(!root) return 0;
    if(!root->left && !root->right) return root->val;
    int left = find(root->left);
    int right = find(root->right);
    int maxn = root->val;
    if(root->left) maxn = maxn+find(root->left->left)+find(root->left->right);  //当前结点值+左节点的孩子的最大金额
    if(root->right) maxn = maxn+find(root->right->left)+find(root->right->right); //当前结点值+右节点的孩子的最大金额
    return max(maxn,left+right);
}

class Solution {
public:
    int rob(TreeNode* root) {
        int ans = find(root);
        return ans;
    }
};
Published 34 original articles · won praise 0 · Views 570

Guess you like

Origin blog.csdn.net/Luyoom/article/details/104962080