class Solution {
public int rob(TreeNode root) {
int[] res = new int[2];
res = robAction(root);
return Math.max(res[0],res[1]);
}
public int[] robAction(TreeNode node){
int res[] = new int[2];
if(node == null) return res;
int[] left = robAction(node.left);
int[] right = robAction(node.right);
res[1] = node.val + left[0] + right[0];
res[0] = Math.max(left[1],left[0]) + Math.max(right[0],right[1]);
return res;
}
}
树形dp入门啊,后序遍历,记录偷1,不偷0,两个状态,取最大值不断dp即可
这篇博客介绍了如何使用动态规划方法解决树形结构的打家劫舍问题(337.打家劫舍III),通过后序遍历记录偷窃和不偷两种状态,求解最大收益。理解了这个算法,有助于入门树形dp并掌握递归与状态转移的思想。

被折叠的 条评论
为什么被折叠?



