We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 156f7a6 commit 908fd6cCopy full SHA for 908fd6c
notes/Leetcode 题解 - 树.md
@@ -427,13 +427,18 @@ Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
427
```
428
429
```java
430
+Map<TreeNode, Integer> cache = new HashMap<>();
431
+
432
public int rob(TreeNode root) {
433
if (root == null) return 0;
434
+ if (cache.containsKey(root)) return cache.get(root);
435
int val1 = root.val;
436
if (root.left != null) val1 += rob(root.left.left) + rob(root.left.right);
437
if (root.right != null) val1 += rob(root.right.left) + rob(root.right.right);
438
int val2 = rob(root.left) + rob(root.right);
- return Math.max(val1, val2);
439
+ int res = Math.max(val1, val2);
440
+ cache.put(root, res);
441
+ return res;
442
}
443
444
0 commit comments