Below is the code that I'm using to find the minimum height of a Binary Search Tree (BST). Original source is here. The definition of minimum height used here is the distance from the root node to the first leaf node that does not contain two children. Through my heavy use of console.logs, I've understood all but the second to last update of the heights.
If you run the code below, the fifth to last log indicates that: Right is -1 and left is -1, which I understand. However, the log after it indicates updating the value of the 'right' recursive call, setting the value of right to 'right + 1.' (Since right was -1. -1 + 1 = 0)
As such, I expect the following: Left = -1, Right = 0.
After the final recursive call, setting right to right + 1 again, I expect the final result to be Left: -1, right: 1.
However, the output is: Left 0, Right: 0. Then after the final update, Left: 0, Right: 1.
So, what am I missing? How are the left and right variables getting updated at the same time?
/* Binary Search Tree */
class Node {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
}
class BST {
constructor() {
this.root = null;
}
add(data) {
const node = this.root;
if (node === null) {
this.root = new Node(data);
return;
} else {
const searchTree = function(node) {
if (data < node.data) {
if (node.left === null) {
node.left = new Node(data);
return;
} else if (node.left !== null) {
return searchTree(node.left);
}
} else if (data > node.data) {
if (node.right === null) {
node.right = new Node(data);
return;
} else if (node.right !== null) {
return searchTree(node.right);
}
} else {
return null;
}
};
return searchTree(node);
}
}
findMinHeight(node = this.root) {
if (node == null) {
console.log("Minus 1")
return -1;
};
console.log("Direction: L on node ", node.data);
let left = this.findMinHeight(node.left);
console.log("Direction: R on node ", node.data);
let right = this.findMinHeight(node.right);
console.log("RIGHT", right, "left", left)
if (left < right) {
console.log('Result = the value of LEFT + 1');
return left + 1;
} else {
console.log('Result = the value of right + 1');
return right + 1;
};
}
}
const bst = new BST();
bst.add(9);
bst.add(4);
bst.add(17);
bst.add(3);
// bst.add(6);
// bst.add(22);
// bst.add(5);
// bst.add(7);
// bst.add(20);
console.log(bst.findMinHeight());