Skip to content

Commit 270d28b

Browse files
committed
Added solution to ch4-2 and associated tests.
1 parent 8400d9a commit 270d28b

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/chapter4/ch4-q02.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'use strict';
2+
import { Tree } from './helpers';
3+
4+
function add(tree, values, start, end) {
5+
if (start === end) {
6+
tree.add(values[start]);
7+
}
8+
else if (start < end) {
9+
let mid = start + Math.floor((end - start) / 2);
10+
tree.add(values[mid]);
11+
add(tree, values, start, mid - 1);
12+
add(tree, values, mid + 1, end);
13+
}
14+
}
15+
16+
export function makeBalancedTree(values) {
17+
let tree = new Tree();
18+
if (values && values.length) {
19+
add(tree, values, 0, values.length - 1);
20+
}
21+
return tree;
22+
}

src/chapter4/ch4-q02.spec.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { expect } from 'chai';
2+
import * as helpers from './helpers';
3+
import * as funcs from './ch4-q02';
4+
5+
for (let key in funcs) {
6+
let func = funcs[key];
7+
8+
describe('ch4-q02: ' + key, function() {
9+
10+
it('returns empty tree with no values', function() {
11+
let tree = func(null);
12+
expect(tree.root).to.be.null;
13+
tree = func([]);
14+
expect(tree.root).to.be.null;
15+
});
16+
17+
it('returns tree with root node set with one value', function() {
18+
let tree = func([10]);
19+
expect(tree.root.val).to.equal(10);
20+
});
21+
22+
it('returns a balanced tree with 10 nodes', function() {
23+
let tree = func([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
24+
expect(helpers.isBalanced(tree)).to.be.true;
25+
});
26+
27+
it('returns a balanced tree with 13 nodes', function() {
28+
let tree = func([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
29+
expect(helpers.isBalanced(tree)).to.be.true;
30+
});
31+
32+
it('returns a balanced tree with 255 nodes', function() {
33+
let values = [];
34+
for (let i = 1; i <= 255; ++i) {
35+
values.push(i);
36+
}
37+
let tree = func(values);
38+
expect(helpers.isBalanced(tree)).to.be.true;
39+
});
40+
41+
});
42+
43+
}

0 commit comments

Comments
 (0)