-
Notifications
You must be signed in to change notification settings - Fork 0
/
bstFindMin.js
43 lines (35 loc) · 1.06 KB
/
bstFindMin.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
// Given the root node of a binary search tree, return the minimum integer value in the tree.
class BinarySearchTreeNode {
constructor(val) {
this.val = val;
this.leftChild = null;
this.rightChild = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
addNode(newValue) {
!this.root ? this.root = new BinarySearchTreeNode(newValue) : this.insert(this.root, newValue);
}
insert(currentNode, newValue) {
if (!currentNode) {
currentNode = new BinarySearchTreeNode(newValue);
} else if (newValue < currentNode.val) {
currentNode.leftChild = this.insert(currentNode.leftChild, newValue);
} else {
currentNode.rightChild = this.insert(currentNode.rightChild, newValue);
}
return currentNode;
}
getMin(currentNode = this.root) {
if (!currentNode.leftChild) return console.log(`Minimum integer in BST: ${currentNode.val}`);
return this.getMin(currentNode.leftChild);
}
}
const myBST = new BinarySearchTree();
myBST.addNode(50);
myBST.addNode(25);
myBST.addNode(75);
myBST.getMin();