Solution not passing tests for some reason: Find the Minimum and Maximum Value in a Binary Search Tree

Greetings, I believe I have solved this problem. I have tested my solution elsewhere and it works fine, but for some reason the following two tests aren’t passing on FCC:

  • The findMin method should return the minimum value in the binary search tree.

  • The findMax method should return the maximum value in the binary search tree.

Link to the challenge: https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/find-the-minimum-and-maximum-value-in-a-binary-search-tree

Here is my code:

// Only change code below this line
  this.findMin = function(){
    if(this.root === null){
      return null;
    } else {
      let current = this.root;
      let moveLeft = function(){
        if(current.left !== null){
          current = current.left;
          moveLeft();
        } else if(current.left === null){
          return current.value;
        }
      }
      moveLeft();
    }
  }
  this.findMax = function(){
    if(this.root === null){
      return null;
    } else {
      let current = this.root;
      let moveRight = function(){
      if(current.right !== null){
        current = current.right;
        moveRight();
        } else if (current.right === null){
          return current.value;
        }
      }
      moveRight();
    }

  }
  // Only change code above this line

Am I missing something? Thank you.

1 Like

There’s slight detail - consider what findMin, findMax and moveLeft, moveRight can return.

Ahh thank you so much! This will help me with the next challenge as well.

For anyone struggling, here’s the spoiler:

// Only change code below this line
  this.findMin = function(){
    if(this.root === null){
      return null;
    } else{
      let current = this.root;
      let moveLeft = function(){
        if(current.left !== null){
          current = current.left;
          moveLeft();
        } else if(current.left === null){
          return current.value;
        }
      }
      moveLeft();
      return moveLeft();
    }
  }
  this.findMax = function(){
    if(this.root === null){
      return null;
    } else {
      let current = this.root;
      let moveRight = function(){
      if(current.right !== null){
        current = current.right;
        moveRight();
        } else if (current.right === null){
          return current.value;
        }
      }
      moveRight();
      return moveRight();
    }

  }
  // Only change code above this line

That’s a step in the right direction, two small notes though. This applies to both moveLeft and moveRight functions.

      moveLeft();
      return moveLeft();

The first moveLeft() call isn’t really needed here and it can, in some cases, call function more than needed.

And when calling moveLeft recursively from within moveLeft, return should be used with it too. This is currently working because of duplicate call mentioned above.

1 Like