forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (44 loc) · 1.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const Node = require('./Node');
class BinarySearchTree {
constructor(value) {
this.root = new Node(value);
}
insert(root, value) {
if (root === null) {
const newNode = new Node(value);
// eslint-disable-next-line no-param-reassign
root = newNode;
return root;
}
if (value < root.value) {
// go left
// eslint-disable-next-line no-param-reassign
root.leftChild = this.insert(root.leftChild, value);
return root;
}
if (value > root.value) {
// go right
// eslint-disable-next-line no-param-reassign
root.rightChild = this.insert(root.rightChild, value);
return root;
}
return root;
}
preorder(root) {
if (root === null) return;
// eslint-disable-next-line no-console
console.log(`${root.value} `);
this.preorder(root.leftChild);
this.preorder(root.rightChild);
}
}
// const bst = new BinarySearchTree(10);
// console.log(bst.root);
// bst.insert(bst.root, 12);
// bst.insert(bst.root, 9);
// bst.insert(bst.root, 19);
// bst.insert(bst.root, 11);
// bst.insert(bst.root, 6);
// console.log(bst.root);
// bst.preorder(bst.root);
module.exports = BinarySearchTree;