-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree.js
55 lines (49 loc) · 1.08 KB
/
Tree.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
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
this.parent = null;
}
}
class BST {
constructor() {
this.root = null;
}
insert(value) {
if (!this.root) {
return (this.root = new Node(value));
}
let currentNode = this.root;
function fn() {
if (currentNode.value > value) {
if (!currentNode.left) {
const newNode = new Node(value);
currentNode.left = newNode;
newNode.parent = currentNode;
} else {
currentNode = currentNode.left;
fn();
}
} else {
if (!currentNode.right) {
const newNode = new Node(value);
currentNode.right = newNode;
newNode.parent = currentNode;
} else {
currentNode = currentNode.right;
fn();
}
}
}
fn();
}
}
const bst = new BST();
bst.insert(10);
bst.insert(4);
bst.insert(8);
bst.insert(22);
bst.insert(34);
bst.insert(28);
console.dir(bst, { depth: 10 });