Skip to content

Commit e224c2b

Browse files
author
lewis617
committed
Add rob to Tree
1 parent 293cae7 commit e224c2b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Tree/BinarySearchTree.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,27 @@ function BinarySearchTree() {
133133
}
134134
}
135135
};
136+
/**
137+
* 打家劫舍问题:房屋按二叉树来排列,
138+
* 不允许在同一晚打劫相邻的两家,
139+
* 求能打劫到的最大钱财数量。
140+
*/
141+
this.rob = function () {
142+
var dfs = function(node){
143+
if(node === null){
144+
return [null, null];
145+
}
146+
var left = dfs(node.left);
147+
var right = dfs(node.right);
148+
var res = [];
149+
res[0] = left[1] + right[1] + node.key;
150+
res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
151+
return res;
152+
};
153+
154+
var num = dfs(root);
155+
return Math.max(num[0], num[1]);
156+
};
136157

137158
var minNode = function (node) {
138159
if (node) {

Tree/BinarySearchTree.test.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ test('BinarySearchTree', function () {
1717
expect(binarySearchTree.values('postOrderTraverse')).toEqual([3, 5, 9, 7, 13, 11]);
1818
expect(binarySearchTree.values('postOrderTraverseUnRec')).toEqual([3, 5, 9, 7, 13, 11]);
1919

20+
expect(binarySearchTree.rob()).toBe(27);
21+
2022
expect(binarySearchTree.min()).toBe(3);
2123
expect(binarySearchTree.max()).toBe(13);
2224
expect(binarySearchTree.search(3)).toBeTruthy();

0 commit comments

Comments
 (0)