我的错误解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int sum = 0;
public int rob(TreeNode root) {
traverse(root,1);
int tmpSum =sum;
//System.out.println(tmpSum);
sum = 0;
traverse(root,0);
return tmpSum<sum?sum:tmpSum;
}
public int traverse(TreeNode root,int color){
if(root == null) return 0;
if(color == 1) sum +=root.val;
traverse(root.left,color^1);
traverse(root.right,color^1);
return 1;
}
}
方法一:
动态规划
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
if(root == null) return 0;
int money = root.val;
if(root.left !=null){
money += rob(root.left.left)+rob(root.left.right);
}
if(root.right !=null){
money +=rob(root.right.left)+rob(root.right.right);
}
int sonsMoney = rob(root.left) +rob(root.right);
return Math.max(money,sonsMoney);
}
}