Data Structures: Find the Minimum and Maximum Height of a Binary Search Tree
This commit is contained in:
parent
487a710719
commit
0e82393bfc
49
Data Structures/bstMinMaxHeight.js
Normal file
49
Data Structures/bstMinMaxHeight.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
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
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user