Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b89e406

Browse files
committedApr 3, 2018
Add binary search tree.
1 parent c5bccff commit b89e406

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed
 

‎src/data-structures/tree/binary-search-tree/BinarySearchTree.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,27 @@ export default class BinarySearchTree {
1313
return this.root.contains(value);
1414
}
1515

16+
remove(value) {
17+
const nodeToRemove = this.findNode(value);
18+
19+
if (!nodeToRemove) {
20+
throw new Error('Item not found in the tree');
21+
}
22+
23+
if (!nodeToRemove.left && !nodeToRemove.right) {
24+
// Node is a leaf and thus has no children.
25+
// Just remove the pointer to this node from the parent node.
26+
} else if (nodeToRemove.left && nodeToRemove.right) {
27+
// Node has two children.
28+
// Find the next biggest value (minimum value in the right branch)
29+
// and replace current value node with that next biggest value.
30+
} else {
31+
// Node has only one child.
32+
// Make this child to be a direct child of current node's parent.
33+
}
34+
}
35+
1636
toString() {
17-
this.root.toString();
37+
return this.root.toString();
1838
}
1939
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,34 @@
1+
import BinarySearchTree from '../BinarySearchTree';
2+
13
describe('BinarySearchTree', () => {
24
it('should create binary search tree', () => {
5+
const bst = new BinarySearchTree();
6+
7+
expect(bst).toBeDefined();
8+
expect(bst.root).toBeDefined();
9+
expect(bst.root.value).toBeNull();
10+
expect(bst.root.left).toBeNull();
11+
expect(bst.root.right).toBeNull();
12+
});
13+
14+
it('should insert values', () => {
15+
const bst = new BinarySearchTree();
16+
17+
bst.insert(10);
18+
bst.insert(20);
19+
bst.insert(5);
20+
21+
expect(bst.toString()).toBe('5,10,20');
22+
});
23+
24+
it('should check if value exists', () => {
25+
const bst = new BinarySearchTree();
26+
27+
bst.insert(10);
28+
bst.insert(20);
29+
bst.insert(5);
330

31+
expect(bst.contains(20)).toBeTruthy();
32+
expect(bst.contains(40)).toBeFalsy();
433
});
534
});

0 commit comments

Comments
 (0)
Please sign in to comment.