|
| 1 | +/** |
| 2 | + * 337. House Robber III |
| 3 | + * https://leetcode.com/problems/house-robber-iii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * The thief has found himself a new place for his thievery again. There is only one |
| 7 | + * entrance to this area, called root. |
| 8 | + * |
| 9 | + * Besides the root, each house has one and only one parent house. After a tour, the smart |
| 10 | + * thief realized that all houses in this place form a binary tree. It will automatically |
| 11 | + * contact the police if two directly-linked houses were broken into on the same night. |
| 12 | + * |
| 13 | + * Given the root of the binary tree, return the maximum amount of money the thief can rob |
| 14 | + * without alerting the police. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * Definition for a binary tree node. |
| 19 | + * function TreeNode(val, left, right) { |
| 20 | + * this.val = (val===undefined ? 0 : val) |
| 21 | + * this.left = (left===undefined ? null : left) |
| 22 | + * this.right = (right===undefined ? null : right) |
| 23 | + * } |
| 24 | + */ |
| 25 | +/** |
| 26 | + * @param {TreeNode} root |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var rob = function(root) { |
| 30 | + return Math.max(...traverse(root)); |
| 31 | + |
| 32 | + function traverse(node) { |
| 33 | + if (!node) return [0, 0]; |
| 34 | + const [l1, l2] = traverse(node.left); |
| 35 | + const [r1, r2] = traverse(node.right); |
| 36 | + return [node.val + l2 + r2, Math.max(l1 + r1, l2 + r2, l1 + r2, l2 + r1)]; |
| 37 | + } |
| 38 | +}; |
0 commit comments