Continuing the discussion from freeCodeCamp Challenge Guide: Find the Minimum and Maximum Value in a Binary Search Tree:
Hints:
- Hint for
.findMax()
: The right side always will have the higher value - Hint for
.findMin()
: The left side always will have the smaller value - Hint to get the value: The smallest value will be when there is no more right side or right side
==null
, same for left side
Solution:
Solution
var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.findMin = (node = this.root)=>{
if(!node){
return null;
}else{
while(node){
if(node.left == null){
return node.value
}
node = node.left
}
}
}
//recursive solution
this.findMax = (root = this.root)=>{
if(!root){
return null;
}else{
if(root.right ==null){
return root.value;
}else{
return this.findMax(root.right)
}
}
}
}