题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0381ca1eadae9ada3d6a505963059d23.png)
解题
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2494ebe4e4cbd32896949b465498db0e.png)
var rob = function(root) {
const f = new Map();
const g = new Map();
const dfs = (root) => {
if (root === null) return;
dfs(root.left);
dfs(root.right);
f.set(root, root.val + (g.get(root.left) || 0) + (g.get(root.right) || 0));
g.set(root, Math.max(f.get(root.left) || 0, g.get(root.left) || 0) + Math.max(f.get(root.right) || 0, g.get(root.right) || 0));
};
dfs(root);
return Math.max(f.get(root) || 0, g.get(root) || 0);
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2c92afd483ae8468fd616ea34a94fab2.png)
var rob = function(root) {
const dfs = (root) => {
if (root === null) return [0, 0];
const [lSelected, lNoSelected] = dfs(root.left);
const [rSelected, rNoSelected] = dfs(root.right);
const selected = root.val + lNoSelected + rNoSelected;
const noSelected = Math.max(lSelected, lNoSelected) + Math.max(rSelected, rNoSelected);
return [selected, noSelected];
};
const rootStatus = dfs(root);
return Math.max(...rootStatus);
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/191c0ee345760048b5c6b64a8603a857.png)