Solution for Find the Minimum and Maximum Value in a Binary Search Tree

Continuing the discussion from freeCodeCamp Challenge Guide: Find the Minimum and Maximum Value in a Binary Search Tree:

Hints:

  1. Hint for .findMax(): The right side always will have the higher value
  2. Hint for .findMin(): The left side always will have the smaller value
  3. 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)
      }
    }
  }
}

Hi @thonker86!

For guide contributions, please include all of the code for the challenge, not just the solution.

When I tried to run your code, there was a syntax error that popped up.
You are missing a curly brace at the end of the findMin solution.

sorry didn’t notice that
thought if I split them it would be clearer as a guide
will fix it and include all the code as one block

Hi @thonker86! I came to nearly the exact solution, but I found using the ternary operator in this case much more readable:

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 = (root = this.root) => {
    if (!this.root) return null;
    return root.left ? this.findMin(root.left) : root.value;
  }
  this.findMax = (root = this.root) => {
    if (!this.root) return null;
    return root.right ? this.findMax(root.right) : root.value;
  }
}
1 Like

This solution needs some minor style editing and the missing } mentioned bae, but otherwise seems reasonable to add to the guide.

I’ll wait to add once other moderators can chime in with opinions