I'm following along this JS data structures video from udemy on Binary search trees. We've got a method to find the max value through recursion.
I was thinking more of comparing all the numbers such as
BST.prototype.getMaxVal = function() {
let num = null;
if (num === null) num = this.value;
else if (this.value > num) num = this.value;
if (this.left) return this.left.getMaxVal();
return num;
}
but the answer is
BST.prototype.getMaxVal = function() {
if (this.right) return this.right.getMaxVal();
else return this.value;
}
105 is the last number without its own leaf, but this method finds 107 before it? how does it find that without any comparison logic?
function BST(value) {
this.value = value;
this.left = null;
this.right = null;
}
BST.prototype.insert = function(value) {
if (value <= this.value) {
if (!this.left) this.left = new BST(value);
else this.left.insert(value);
} else {
if (!this.right) this.right = new BST(value);
else this.right.insert(value);
}
return this;
}
const bst = new BST(50);
bst.insert(30);
bst.insert(70);
bst.insert(107);
bst.insert(60);
bst.insert(59);
bst.insert(20);
bst.insert(45);
bst.insert(35);
bst.insert(85);
bst.insert(105);
bst.insert(10);
bst.getMaxVal();

insertmethod. Then you know that obj.left will always be lower and obj.right will always be higher.bst(50) values that are lower than 50 will be set on the left hand of this object, and if a new value is lower than the previously set lower val, then its own left will hold this new lower val. And in case the entry point is the lowest value, it just returns itself.