1. 题目
2. 思路
(1) 递归+动态规划
- 为二叉树中的每个结点定义一个状态数组status,status[0]表示盗取该结点的以该结点为根的最高金额,status[1]表示不盗取该结点的以该结点为根的最高金额。
- 利用递归深度优先搜索每个结点,获取每个子结点的状态数组status。
- 对于根结点,status[0]等于该结点的值加上左右子结点的status[1]的值,status[1]等于左右子结点的最高金额之和。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int rob(TreeNode root) {
int[] status = dfs(root);
return Math.max(status[0], status[1]);
}
public int[] dfs(TreeNode node) {
if (node == null) {
return new int[]{0, 0};
}
int[] left = dfs(node.left);
int[] right = dfs(node.right);
int selected = node.val + left[1] + right[1];
int notSelected = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return new int[]{selected, notSelected};
}
}