-
Notifications
You must be signed in to change notification settings - Fork 0
/
bstFindMax.js
45 lines (37 loc) · 1.05 KB
/
bstFindMax.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
// Given the root node of a binary search tree, return the maximum 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(newVal) {
!this.root ? this.root = new BinarySearchTreeNode(newVal) : this.insert(this.root, newVal);
}
insert(currentNode, newVal) {
if (!currentNode) {
currentNode = new BinarySearchTreeNode(newVal);
} else if (newVal < currentNode.val) {
currentNode.leftChild = this.insert(currentNode.leftChild, newVal);
} else {
currentNode.rightChild = this.insert(currentNode.rightChild, newVal);
}
return currentNode;
}
getMax(currentNode = this.root) {
if (!currentNode.rightChild) {
return console.log(`Found max value: ${currentNode.val}`);
}
return this.getMax(currentNode.rightChild);
}
}
const myBST = new BinarySearchTree();
myBST.addNode(50);
myBST.addNode(25);
myBST.addNode(75);
myBST.getMax();