Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite3eb03b

Browse files
committed
Update JavaScript code for Balanced Binary Tree
The JavaScript solution for 110 - Balanced Binary Tree currentlyavailable on the NeetCode.io website is inefficient, with a timecomplexity of O(n^2). I have updated the solution to reflect theoriginal Python solution as presented in the video.
1 parentca7dbc4 commite3eb03b

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-
varisBalanced=function(root){
14-
if(!root)returntrue
15-
constleft=findHeight(root.left)
16-
constright=findHeight(root.right)
17-
returnMath.abs(left-right)<=1&&isBalanced(root.left)&&isBalanced(root.right)
18-
};
13+
varisBalanced=function(root){
14+
constgetHeight=(root)=>{
15+
if(!root)return[-1,true];
1916

20-
functionfindHeight(node){
21-
if(node==null)return0;
22-
return1+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+
constbalanced=leftBalanced&&rightBalanced&&Math.abs(leftHeight-rightHeight)<2;
21+
22+
return[1+Math.max(leftHeight,rightHeight),balanced];
23+
};
24+
25+
constbalanced=getHeight(root)[1]
26+
27+
returnbalanced;
28+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp