1、力扣原题
https://leetcode-cn.com/problems/house-robber-iii/
- 思路:爷爷、儿子、孙子
要么爷爷出钱,儿子就不出钱
要么爷爷不出去,就从让儿子上交钱
取最大的值
class Solution {
public int rob(TreeNode root) {
int[] res = recursionRob(root);
return Math.max(res[0],res[1]);
}
public int[] recursionRob(TreeNode root) {
if (root == null) return new int[2];
int[] result = new int[2];
int[] leftRes = recursionRob(root.left);
int[] rightRes = recursionRob(root.right);
// 爷爷家不用上交钱,只要两个儿子分别上交的钱最多就行,至于儿子的钱筹划方案怎么来的,我不管
result[0] = Math.max(leftRes[0],leftRes[1]) + Math.max(rightRes[0],rightRes[1]);
// 爷爷家上交钱,儿子就肯定不用交钱
result[1] = leftRes[0] + rightRes[0] + root.val;
return result;
}
}