From e3eb03b9d1b72e0775c1a28f9f885a25fb77a032 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 11 Jul 2022 21:21:13 +0530 Subject: [PATCH] Update JavaScript code for Balanced Binary Tree The JavaScript solution for 110 - Balanced Binary Tree currently available on the NeetCode.io website is inefficient, with a time complexity of O(n^2). I have updated the solution to reflect the original Python solution as presented in the video. --- javascript/110-Balanced-Binary-Tree.js | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/javascript/110-Balanced-Binary-Tree.js b/javascript/110-Balanced-Binary-Tree.js index 0f492c0c1..ba9665fe7 100644 --- a/javascript/110-Balanced-Binary-Tree.js +++ b/javascript/110-Balanced-Binary-Tree.js @@ -10,17 +10,19 @@ * @param {TreeNode} root * @return {boolean} */ - var isBalanced = function (root) { - if (!root) return true - const left = findHeight(root.left) - const right = findHeight(root.right) - return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right) -}; +var isBalanced = function (root) { + const getHeight = (root) => { + if (!root) return [-1, true]; -function findHeight(node) { - if (node == null) return 0; - return 1 + Math.max(this.findHeight(node.left), this.findHeight(node.right)); -} + const [leftHeight, leftBalanced] = getHeight(root.left); + const [rightHeight, rightBalanced] = getHeight(root.right); -// Runtime: 78 ms, faster than 90.43% of JavaScript online submissions for Balanced Binary Tree. -// Memory Usage: 47.1 MB, less than 32.41% of JavaScript online submissions for Balanced Binary Tree. \ No newline at end of file + const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) < 2; + + return [1 + Math.max(leftHeight, rightHeight), balanced]; + }; + + const balanced = getHeight(root)[1] + + return balanced; +}; \ No newline at end of file pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy