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

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

#1

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
}
``````