File tree Expand file tree Collapse file tree 1 file changed +14
-12
lines changed Expand file tree Collapse file tree 1 file changed +14
-12
lines changed Original file line number Diff line number Diff line change 10
10
* @param {TreeNode } root
11
11
* @return {boolean }
12
12
*/
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 ] ;
19
16
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 ) ;
24
19
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
+ } ;
You can’t perform that action at this time.
0 commit comments