/
bst.js
135 lines (109 loc) · 2.52 KB
/
bst.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
Based on: https://khan4019.github.io/front-end-Interview-Questions/bst.html
*/
// To create a Binary Search Tree:
// Create a node:
function Node(val) {
this.value = val
this.left = null
this.right = null
}
// Create a constructor for the BST
function BinarySearchTree() {
this.root = null
}
/*
The structure of a Binary Search Tree is as follows:
- Every node value on the left is smaller than the parent node (root)
- Every node value on the right is larger than the parent node (root)
This would require you to find the appropriate location when inserting
*/
BinarySearchTree.prototype.push = function(val) {
var root = this.root
if (!root) {
this.root = new Node(val)
return
}
var currentNode = root
var newNode = new Node(val)
while(currentNode) {
if (val < currentNode.value) {
if(!currentNode.left) {
currentNode.left = newNode
break
} else {
currentNode = currentNode.left
}
} else {
if (!currentNode.right) {
currentNode.right = newNode
break
} else {
currentNode = currentNode.right
}
}
}
}
// Pre Order Traversal
function preOrder(node) {
if (node) {
console.log(node.value)
preOrder(node.left)
preOrder(node.right)
}
}
// In Order Traversal
function inOrder(node) {
if (node) {
inOrder(node.left)
console.log(node.value)
inOrder(node.right)
}
}
// Post Order Traversal
function postOrder(node) {
if (node) {
postOrder(node.left)
postOrder(node.right)
console.log(node.value)
}
}
// Min Value
function minNode(node) {
if (!node) {
return 0
}
if (node.left) {
return minNode(node.left)
}
return node.value
}
// Max Value
function maxNode(node) {
if (!node) {
return 0
}
if (node.right) {
return maxNode(node.right)
}
return node.value
}
// Create instance of BST
var bst = new BinarySearchTree()
// Push values to BST
bst.push(40)
bst.push(25)
bst.push(10)
bst.push(32)
bst.push(78)
// Call methods
console.log("Pre order traversal: ");
preOrder(bst.root)
console.log("\nIn order traversal: ");
inOrder(bst.root)
console.log("\nPost order traversal: ");
postOrder(bst.root)
console.log("\nMin Value: ");
console.log(minNode(bst.root));
console.log("\nMax Value: ");
console.log(maxNode(bst.root));