diff --git a/notes/Leetcode 题解 - 树.md b/notes/Leetcode 题解 - 树.md index 410553f7..c0243939 100644 --- a/notes/Leetcode 题解 - 树.md +++ b/notes/Leetcode 题解 - 树.md @@ -427,13 +427,18 @@ Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. ``` ```java +Map cache = new HashMap<>(); + public int rob(TreeNode root) { if (root == null) return 0; + if (cache.containsKey(root)) return cache.get(root); int val1 = root.val; if (root.left != null) val1 += rob(root.left.left) + rob(root.left.right); if (root.right != null) val1 += rob(root.right.left) + rob(root.right.right); int val2 = rob(root.left) + rob(root.right); - return Math.max(val1, val2); + int res = Math.max(val1, val2); + cache.put(root, res); + return res; } ```