1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public int rob(TreeNode root) { Map<TreeNode, Integer> notRobMoneyCache = new IdentityHashMap<>(); Map<TreeNode, Integer> robMoneyCache = new IdentityHashMap<>();
return rob(root, false, notRobMoneyCache, robMoneyCache); }
private int rob(TreeNode node, boolean parentRobbed, Map<TreeNode, Integer> notRobMoneyCache, Map<TreeNode, Integer> robMoneyCache) { if (node == null) { return 0; }
Integer cachedNotRobMoney = notRobMoneyCache.get(node); int notRobMoney; if (cachedNotRobMoney != null) { notRobMoney = cachedNotRobMoney; } else { notRobMoney = rob(node.left, false, notRobMoneyCache, robMoneyCache) + rob(node.right, false, notRobMoneyCache, robMoneyCache); notRobMoneyCache.put(node, notRobMoney); }
int robMoney = 0; if (!parentRobbed) { Integer cachedRobMoney = robMoneyCache.get(node); if (cachedRobMoney != null) { robMoney = cachedRobMoney; } else { robMoney += node.val; if (node.left != null) { robMoney += rob(node.left, true, notRobMoneyCache, robMoneyCache); } if (node.right != null) { robMoney += rob(node.right, true, notRobMoneyCache, robMoneyCache); } robMoneyCache.put(node, robMoney); } }
return Math.max(notRobMoney, robMoney); } }
|