File tree Expand file tree Collapse file tree 2 files changed +50
-1
lines changed
src/data-structures/tree/binary-search-tree Expand file tree Collapse file tree 2 files changed +50
-1
lines changed Original file line number Diff line number Diff line change @@ -13,7 +13,27 @@ export default class BinarySearchTree {
13
13
return this . root . contains ( value ) ;
14
14
}
15
15
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
+
16
36
toString ( ) {
17
- this . root . toString ( ) ;
37
+ return this . root . toString ( ) ;
18
38
}
19
39
}
Original file line number Diff line number Diff line change
1
+ import BinarySearchTree from '../BinarySearchTree' ;
2
+
1
3
describe ( 'BinarySearchTree' , ( ) => {
2
4
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 ) ;
3
30
31
+ expect ( bst . contains ( 20 ) ) . toBeTruthy ( ) ;
32
+ expect ( bst . contains ( 40 ) ) . toBeFalsy ( ) ;
4
33
} ) ;
5
34
} ) ;
You can’t perform that action at this time.
0 commit comments