From 0e82393bfcdd67fa3412845bb91f11916046c700 Mon Sep 17 00:00:00 2001 From: Manish Date: Thu, 31 Aug 2023 16:06:39 +1000 Subject: [PATCH] Data Structures: Find the Minimum and Maximum Height of a Binary Search Tree --- Data Structures/bstMinMaxHeight.js | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Data Structures/bstMinMaxHeight.js 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 +}