Brush Questions-Leetcode-337. House Robbery III (recursion, tree)

337. House Robbery III

Topic link

Source: LeetCode
Link: https://leetcode-cn.com/problems/house-robber-iii/

Title description

After robbing a street and a circle of houses last time, the thief discovered a new area where theft could be done. There is only one entrance to this area, which we call the "root". In addition to the "root", every house has one and only one "parent" house connected to it. After some reconnaissance, the clever thief realized that "the arrangement of all the houses in this place is similar to a binary tree." If two directly connected houses are robbed on the same night, the house will automatically call the police.

Calculate the maximum amount a thief can steal in one night without triggering the alarm.

Example 1:

Input: [3,2,3,null,3,null,1]

 3
/ \

2 3
\ \
3 1

Output: 7
Explanation: The maximum amount a thief can steal in one night = 3 + 3 + 1 = 7.
Example 2:

Input: [3,4,5,1,3,null,1]

 3
/ \

4 5
/ \ \
1 3 1

Output: 9
Explanation: The maximum amount a thief can steal in one night = 4 + 5 = 9.

Topic analysis

Bottom-up recursion.
dp[0]: If the current node does not steal the maximum value
, its left and right nodes can be stolen or not, so dp[0] = the maximum value of its left node (stealing or not stealing) + its right node The maximum value of (to steal or not to steal).
dp[1]: The maximum value stolen by the current node.
If stolen, its left and right nodes cannot be stolen. So dp[1]= its left node does not steal the maximum value + its right node does not steal the maximum value.

[3,2,3,null,3,null,1] exampleInsert picture description here

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public int rob(TreeNode root) {
    
    
        int dp[] = robIntetnal(root);
        return dp[0] > dp[1] ? dp[0] : dp[1];
    }
    public int[] robIntetnal(TreeNode root){
    
    
        if(root==null){
    
    
            return new int[2];
        }
        int left [] = robIntetnal(root.left);
        int right[] = robIntetnal(root.right);

        int dp[] = new int[2];// 0:當前節點不偷的最大值 1:當前節點偷的最大值
        dp[0] = (left[0]>left[1]?left[0]:left[1]) + (right[0]>right[1]?right[0]:right[1]);
        dp[1] = left[0] +right[0] + root.val;
        return dp;
    }
}

Guess you like

Origin blog.csdn.net/qq_42771487/article/details/113108336