/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public Map<TreeNode,Integer> trueCache = new HashMap<TreeNode,Integer>();
public Map<TreeNode,Integer> falseCache = new HashMap<TreeNode,Integer>();
public int dfs(TreeNode root,boolean canRob) {
if(root == null)
return 0;
if(canRob && trueCache.containsKey(root))
return trueCache.get(root);
if(!canRob && falseCache.containsKey(root))
return falseCache.get(root);
int ans = 0;
if(canRob)
ans = Math.max(ans,
root.val + dfs(root.left,false) + dfs(root.right,false));
ans = Math.max(ans,
dfs(root.left,true) + dfs(root.right,true));
if(canRob)
trueCache.put(root,ans);
if(!canRob)
falseCache.put(root,ans);
return ans;
}
public int rob(TreeNode root) {
return dfs(root,true);
}
}