From 28aecb41f82084776f3c023c25d2a9973ac6bc7c Mon Sep 17 00:00:00 2001 From: Dan B Date: Tue, 5 Mar 2019 06:37:57 -0800 Subject: [PATCH] Update find-the-minimum-and-maximum-height-of-a-binary-search-tree.english.md (#35006) Added working solution to the problem --- ...-height-of-a-binary-search-tree.english.md | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/curriculum/challenges/english/08-coding-interview-prep/data-structures/find-the-minimum-and-maximum-height-of-a-binary-search-tree.english.md b/curriculum/challenges/english/08-coding-interview-prep/data-structures/find-the-minimum-and-maximum-height-of-a-binary-search-tree.english.md index a5ec049c04..0cd077731b 100644 --- a/curriculum/challenges/english/08-coding-interview-prep/data-structures/find-the-minimum-and-maximum-height-of-a-binary-search-tree.english.md +++ b/curriculum/challenges/english/08-coding-interview-prep/data-structures/find-the-minimum-and-maximum-height-of-a-binary-search-tree.english.md @@ -109,6 +109,56 @@ BinarySearchTree.prototype = {
```js -// solution required +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; + // change code below this line + this.findMinHeight = function(root = this.root) { + if (root === null) { + return -1; + } else if (root.left === null && root.right === null) { + return 0; + } else if (root.left == null) { + return (this.findMinHeight(root.right) + 1); + } else if (root.right == null) { + return (this.findMinHeight(root.left) + 1); + } else { + return Math.min(this.findMinHeight(root.left), this.findMinHeight(root.right)) + 1; + } + } + this.findMaxHeight = function(root = this.root) { + if (root === null) { + return -1; + } else if (root.left === null && root.right === null) { + return 0; + } else if (root.left == null) { + return (this.findMaxHeight(root.right) + 1); + } else if (root.right == null) { + return (this.findMaxHeight(root.left) + 1); + } else { + return Math.max(this.findMaxHeight(root.left), this.findMaxHeight(root.right)) + 1; + } + } + this.isBalanced = function(root = this.root) { + if (root === null || root.left === null || root.right === null) { + return false; + } + let l = this.findMaxHeight(root.left); + let r = this.findMaxHeight(root.right); + let difference = Math.abs(r - l); + if (difference <= 1 && this.isBalanced(root.left) && this.isBalanced(root.right)) { + return false; + } + return true; + } + // change code above this line +} ```