Skip to content

Commit e3eb03b

Browse files
committed
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.
1 parent ca7dbc4 commit e3eb03b

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

javascript/110-Balanced-Binary-Tree.js

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,19 @@
1010
* @param {TreeNode} root
1111
* @return {boolean}
1212
*/
13-
var isBalanced = function (root) {
14-
if (!root) return true
15-
const left = findHeight(root.left)
16-
const right = findHeight(root.right)
17-
return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right)
18-
};
13+
var isBalanced = function (root) {
14+
const getHeight = (root) => {
15+
if (!root) return [-1, true];
1916

20-
function findHeight(node) {
21-
if (node == null) return 0;
22-
return 1 + Math.max(this.findHeight(node.left), this.findHeight(node.right));
23-
}
17+
const [leftHeight, leftBalanced] = getHeight(root.left);
18+
const [rightHeight, rightBalanced] = getHeight(root.right);
2419

25-
// Runtime: 78 ms, faster than 90.43% of JavaScript online submissions for Balanced Binary Tree.
26-
// Memory Usage: 47.1 MB, less than 32.41% of JavaScript online submissions for Balanced Binary Tree.
20+
const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) < 2;
21+
22+
return [1 + Math.max(leftHeight, rightHeight), balanced];
23+
};
24+
25+
const balanced = getHeight(root)[1]
26+
27+
return balanced;
28+
};

0 commit comments

Comments
 (0)
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