diff --git a/Data Structures/bstMinMaxHeight.js b/Data Structures/bstMinMaxHeight.js new file mode 100644 index 0000000..650dc2e --- /dev/null +++ b/Data Structures/bstMinMaxHeight.js @@ -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 +}