Data Structures: Find the Minimum and Maximum Value in a Binary Search Tree

I’m trying to solve this data structure problem (https://learn.freecodecamp.org/coding-interview-prep/data-structures/find-the-minimum-and-maximum-value-in-a-binary-search-tree) and seem to be running on a problem. I’m getting some failed tests though, which states:

  1. The findMin method returns the minimum value in the binary search tree.
  2. The findMax method returns the maximum value in the binary search tree.

I put logs in to keep track of the values and switched the values returned between the actual min and max nodes and their values.

Here’s my code:

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;
    // change code below this line
    this.findMin = function(elem) {
      console.log("findMin method: ");
      var currNode;
      if (this.root != null) {
        if (elem == this.root || elem == undefined) {
          currNode = this.root;
        } else {
          currNode = elem;
        }
        // console.log(currNode);
        if (currNode.left != null) {
          this.findMin(currNode.left);
        } else {
          console.log('found minumum value:');
          console.log(currNode);
          console.log(currNode.value);
          return currNode.value;
        }
      } else {
        return null;
      }
    }

    this.findMax = function(elem) {
      console.log("findMax method: ");
      var currNode;
      if (this.root != null) {
        if (elem == this.root || elem == undefined) {
          currNode = this.root;
        } else {
          currNode = elem;
        }
        // console.log(currNode);
        if (currNode.right != null) {
          this.findMax(currNode.right);
        } else {
          console.log('found maximum value:');
          console.log(currNode);
          console.log(currNode.value);
          return currNode.value;
        }
      } else {
        return null;
      }
    }
    // change code above this line
}

i’m a bit late but calling a function recursively makes that you cannot return value, even though console.log() shows least and most numbers. You need to loop it with while, assigning to currNode variable his left/right property.

Both methods neither receive arguments.
maybe this helps you:

this.findMin = () => {
    let node;
    if (this.root) {
      node = this.root;
      while (node.left !== null) {
        node = node.left;
      }
      return node.value;
    }
  };
1 Like

I’m even later to this party but a while loop isn’t necessarily needed. The OP has forgotten to use return when they call the recursive function. I think the below should also work.

if (currNode.right != null) {
        return  this.findMax(currNode.right);
        }