-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (71 loc) · 1.42 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Node {
constructor(value) {
if (!value) {
throw "Value cannot be null";
} else {
this.value = value;
}
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
if (this.root === null) {
this.root = new Node(value);
} else {
if (value < this.root.value) {
if (!this.left) {
this.left = new BinarySearchTree();
this.left.insert(value);
} else {
this.left.insert(value);
}
}
if (value > this.root.value) {
if (!this.right) {
this.right = new BinarySearchTree();
this.right.insert(value);
} else {
this.right.insert(value);
}
}
}
}
inOrder() {
if (this.root) {
if (this.left) {
this.left.inOrder();
}
console.log(this.root.value);
}
if (this.right) {
this.right.inOrder();
}
}
decOrder() {
if (this.root) {
if (this.right) {
this.right.decOrder();
}
console.log(this.root.value);
}
if (this.left) {
this.left.decOrder();
}
}
}
const BST = new BinarySearchTree();
for (let index = 0; index < 10; index++) {
BST.insert(Math.random().toFixed(2));
}
// BST.insert(2)
// BST.insert(1)
// BST.insert(3)
// BST.insert(4)
// BST.insert(5)
// BST.insert(-1)
// console.log('BST: ', JSON.stringify(BST));
BST.decOrder();
// BST.inOrder()