```
public int rob(TreeNode root) {
if(root==null) return 0;
rob1(root);
return root.val;
}
public int rob1(TreeNode root){
if(root==null) return 0;
int pre=0;
root.val+=rob1(root.left)+rob1(root.right);
if(root.left!=null) pre+=root.left.val;
if(root.right!=null) pre+=root.right.val;
root.val=Math.max(pre,root.val);
return pre;
}
```

The other solution need extra class:

```
class Profit{
int preprofit;
int maxprofit;
Profit(int pre,int max){
preprofit=pre;
maxprofit=max;
}
}
public class Solution {
public int rob(TreeNode root ) {
return rob1(root).maxprofit;
}
public Profit rob1(TreeNode root){
if (root == null) return new Profit(0, 0);
int pre = 0, max = root.val;
Profit left = rob1(root.left), right = rob1(root.right);
max += left.preprofit + right.preprofit;
pre = left.maxprofit + right.maxprofit;
max = Math.max(pre,max);
return new Profit(pre,max);
}
}
```