Skip to content

Commit f32e9aa

Browse files
committed
update: BST insertion added
1 parent 31c5648 commit f32e9aa

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = class Node {
2+
constructor(value) {
3+
this.value = value;
4+
this.leftChild = null; // will be a node
5+
this.rightChild = null; // will be a node
6+
}
7+
};
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const Node = require('./Node');
2+
3+
class BinarySearchTree {
4+
constructor(value) {
5+
this.root = new Node(value);
6+
}
7+
8+
insert(root, value) {
9+
if (root === null) {
10+
const newNode = new Node(value);
11+
// eslint-disable-next-line no-param-reassign
12+
root = newNode;
13+
return root;
14+
}
15+
16+
if (value < root.value) {
17+
// go left
18+
// eslint-disable-next-line no-param-reassign
19+
root.leftChild = this.insert(root.leftChild, value);
20+
return root;
21+
}
22+
if (value > root.value) {
23+
// go right
24+
// eslint-disable-next-line no-param-reassign
25+
root.rightChild = this.insert(root.rightChild, value);
26+
return root;
27+
}
28+
return root;
29+
}
30+
}
31+
32+
// const bst = new BinarySearchTree(10);
33+
// console.log(bst.root);
34+
// bst.insert(bst.root, 12);
35+
// bst.insert(bst.root, 9);
36+
// bst.insert(bst.root, 19);
37+
// bst.insert(bst.root, 11);
38+
// bst.insert(bst.root, 6);
39+
40+
// console.log(bst.root);
41+
42+
module.exports = BinarySearchTree;

0 commit comments

Comments
 (0)