337. House Robber III - jiejackyzhang/leetcode-note GitHub Wiki

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
  / \   \ 
 1   3   1
Maximum amount of money the thief can rob = 4 + 5 = 9.

解题思路为Dynamic Programming。 考虑一个node时,有两种case:

  1. rob:则它的左右孩子都不能rob;
  2. no rob:则它的左右孩子可以rob,也可以不rob。

每一个node都存两个变量,P[NOROB]和P[ROB],分别对应两种case所获取的最大值。 计算顺序由下至上,可采用recursive方式。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static final int NOROB = 0;
    public static final int ROB = 1;
    
    public int rob(TreeNode root) {
        int[] dp = DP(root);
        return Math.max(dp[NOROB], dp[ROB]);
    }
    
    private int[] DP(TreeNode node) {
        if(node == null) return new int[]{0, 0};
        int[] dpLeft = DP(node.left);
        int[] dpRight = DP(node.right);
        int rob = node.val + dpLeft[NOROB] + dpRight[NOROB];
        int norob = Math.max(dpLeft[NOROB], dpLeft[ROB]) + Math.max(dpRight[NOROB], dpRight[ROB]);
        return new int[]{norob, rob};
    }
}
⚠️ **GitHub.com Fallback** ⚠️