(root)
| 14 | */ |
| 15 | var rob = function (root) { |
| 16 | function dfs(root) { |
| 17 | if (!root) return [0, 0]; |
| 18 | |
| 19 | const leftSubTree = dfs(root.left); |
| 20 | const rightSubTree = dfs(root.right); |
| 21 | |
| 22 | const withoutRoot = |
| 23 | Math.max(...leftSubTree) + Math.max(...rightSubTree); |
| 24 | const withRoot = root.val + leftSubTree[0] + rightSubTree[0]; |
| 25 | |
| 26 | return [withoutRoot, withRoot]; |
| 27 | } |
| 28 | |
| 29 | return Math.max(...dfs(root)); |
| 30 | }; |