Skip to content

Commit 144db13

Browse files
committed
Add solution #337
1 parent 3f1afe8 commit 144db13

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,7 @@
245245
328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium|
246246
331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium|
247247
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|
248+
337|[House Robber III](./0337-house-robber-iii.js)|Medium|
248249
338|[Counting Bits](./0338-counting-bits.js)|Easy|
249250
342|[Power of Four](./0342-power-of-four.js)|Easy|
250251
344|[Reverse String](./0344-reverse-string.js)|Easy|

solutions/0337-house-robber-iii.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
 (0)