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 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+ } ;
You can’t perform that action at this time.
0 commit comments