File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
scripts/algorithms/M/Maximum Width of Binary Tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 66 ms (Top 53.29%) | Memory: 47.20 MB (Top 43.11%)
2
+
3
+ var widthOfBinaryTree = function ( root ) {
4
+ if ( ! root ) {
5
+ return 0 ;
6
+ }
7
+ const q = [ [ root , 0 ] ] ;
8
+ let maxWidth = 0 , l = 0 , r = 0 ;
9
+ while ( q . length ) {
10
+ const size = q . length ;
11
+ const startIdx = q [ 0 ] [ 1 ] ;
12
+ for ( let i = 0 ; i < size ; ++ i ) {
13
+ const [ node , idx ] = q . shift ( ) ;
14
+ if ( i === 0 ) {
15
+ l = idx ;
16
+ }
17
+ if ( i === size - 1 ) {
18
+ r = idx ;
19
+ }
20
+ const subIdx = idx - startIdx ;
21
+ if ( node . left !== null ) {
22
+ q . push ( [ node . left , 2 * subIdx + 1 ] ) ;
23
+ }
24
+ if ( node . right !== null ) {
25
+ q . push ( [ node . right , 2 * subIdx + 2 ] ) ;
26
+ }
27
+ }
28
+ maxWidth = Math . max ( maxWidth , r - l + 1 ) ;
29
+ }
30
+ return maxWidth ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments