image.png
image.png

解决思路

动态规划

image.png

  1. public int rob(TreeNode root) {
  2. int[] result = robInternal(root);
  3. return Math.max(result[0],result[1]);
  4. }
  5. private int[] robInternal(TreeNode root){
  6. if (root == null)
  7. return new int[2];
  8. int[] result = new int[2];
  9. int[] left = robInternal(root.left);
  10. int[] right = robInternal(root.right);
  11. result[0] = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
  12. result[1] = left[0] + right[0] + root.val;
  13. return result;
  14. }