50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
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.findMinHeight = () => {
|
|
let height = -1;
|
|
if (this.root === null) return height;
|
|
let q = [this.root];
|
|
let nextQ = [];
|
|
while (q.length) {
|
|
height++;
|
|
for (let node of q) {
|
|
if (node.left === null && node.right === null) {
|
|
return height;
|
|
}
|
|
if (node.left !== null) nextQ.push(node.left);
|
|
if (node.right !== null) nextQ.push(node.right);
|
|
}
|
|
q = nextQ;
|
|
nextQ = [];
|
|
}
|
|
return height;
|
|
};
|
|
this.findMaxHeight = () => {
|
|
let height = -1;
|
|
if (this.root === null) return height;
|
|
let q = [this.root];
|
|
let nextQ = [];
|
|
while (q.length) {
|
|
height++;
|
|
for (let node of q) {
|
|
if (node.left !== null) nextQ.push(node.left);
|
|
if (node.right !== null) nextQ.push(node.right);
|
|
}
|
|
q = nextQ;
|
|
nextQ = [];
|
|
}
|
|
return height;
|
|
};
|
|
this.isBalanced = () => {
|
|
return this.findMaxHeight() - this.findMinHeight() < 2;
|
|
};
|
|
// Only change code above this line
|
|
}
|