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