If I create a tree with min height of 2, the solution (plus an add method) returns a min height of 1. Im using the displayTree function provided in the code, where you can see the tree in the console. Maybe Im missing something here but I believe the tree is correctly displayed, I just think the min height function in incorrect.
Solution code + add function as well as tree construction and display
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;
// Only change code below this line
this.add = function(value) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return undefined;
}
let currentNode = this.root;
while (currentNode) {
if (currentNode.value === newNode.value) {
return null;
}
const direction = currentNode.value > newNode.value ? "left" : "right";
if (!currentNode[direction]) {
currentNode[direction] = newNode;
return undefined;
}
currentNode = currentNode[direction];
}
}
this.findMinHeight = function() {
if (!this.root) return -1;
function findNodeMinHeight(node) {
if (!node) return 0;
return 1 + Math.min(
findNodeMinHeight(node.left),
findNodeMinHeight(node.right)
);
}
return findNodeMinHeight(this.root) - 1;
}
this.findMaxHeight = function() {
if (!this.root) return -1;
function findNodeMaxHeight(node) {
if (!node) return 0;
return 1 + Math.max(
findNodeMaxHeight(node.left),
findNodeMaxHeight(node.right)
);
}
return findNodeMaxHeight(this.root) - 1;
}
this.isBalanced = function() {
return this.findMinHeight() == this.findMaxHeight();
}
// Only change code above this line
}
const p = new BinarySearchTree()
p.add(17)
p.add(4)
p.add(1)
p.add(19)
p.add(33)
p.add(34)
console.log(displayTree(p))
console.log(p.findMinHeight(), "min")
console output:
{
"root": {
"value": 17,
"left": {
"value": 4,
"left": {
"value": 1,
"left": null,
"right": null
},
"right": null
},
"right": {
"value": 19,
"left": null,
"right": {
"value": 33,
"left": null,
"right": {
"value": 34,
"left": null,
"right": null
}
}
}
}
}
undefined
1 min