-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (71 loc) · 1.87 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
77
78
79
80
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BST {
constructor() {
this.root = null;
}
insert(value) {
const node = new TreeNode(value);
if (!this.root) {
this.root = node
} else {
this._insertNode(this.root, node);
}
}
_insertNode(node, newNode) {
if (newNode.value < node.value) {
if (node.left === null) {
node.left = newNode
} else {
this._insertNode(node.left, newNode)
}
} else if (node.value < newNode.value) {
if (node.right === null) {
node.right = newNode
} else {
this._insertNode(node.right, newNode)
}
} else {
console.log('Value already Exists')
}
}
inOrder(node = this.root, result = []) {
if (node !== null) {
this.inOrder(node.left, result);
result.push(node.value);
this.inOrder(node.right, result);
}
return result;
}
preOrder(node = this.root, result = []) {
if (node !== null) {
result.push(node.value);
this.preOrder(node.left, result);
this.preOrder(node.right, result);
}
return result;
}
postOrder(node = this.root, result = []) {
if (node !== null) {
this.postOrder(node.left, result);
this.postOrder(node.right, result);
result.push(node.value);
}
return result;
}
}
const bst = new BST();
bst.insert(1)
bst.insert(2)
bst.insert(3)
bst.insert(4)
bst.insert(5)
// console.log(bst.root)
console.log('Inorder : ', bst.inOrder());
console.log('PreOrder : ', bst.preOrder());
console.log('PostOrder : ', bst.postOrder())