@@ -12,46 +12,45 @@ class TreeNode {
12
12
*/
13
13
const maxLevelSum = ( root ) => {
14
14
let queue = [ root ] , level = 1 , max = root . val , tmpMax = 0 ,
15
- nbOfLeaves = 0 , tmpLeaves = 0 , nodesToVisit = 2 , visitedCount = 0 ;
15
+ nbOfLeaves = 0 , tmpLeaves = 0 , nodesToVisit = 2 , visitedCount = 0 , list = [ ] ;
16
16
17
17
while ( queue . length > 0 ) {
18
18
let curr = queue . shift ( ) , left = curr . left , right = curr . right ;
19
19
console . log ( `> curr:${ curr . val } ` )
20
20
21
21
if ( undefined !== left ) {
22
+ visitedCount ++ ;
22
23
if ( null !== left ) {
23
24
tmpMax += left . val ;
24
25
queue . push ( left ) ;
25
- visitedCount ++ ;
26
26
} else {
27
27
tmpLeaves ++ ;
28
28
}
29
29
}
30
30
31
31
if ( undefined !== right ) {
32
+ visitedCount ++ ;
32
33
if ( null !== right ) {
33
34
tmpMax += right . val ;
34
35
queue . push ( right ) ;
35
- visitedCount ++ ;
36
36
} else {
37
37
tmpLeaves ++ ;
38
38
}
39
39
}
40
40
41
41
console . log ( `old_level:${ level } , tmpMax:${ tmpMax } , max:${ max } , nodesToVisit:${ nodesToVisit } visitedCount:${ visitedCount } , tmpLeaves:${ tmpLeaves } , nbOfLeaves:${ nbOfLeaves } ` )
42
- // if (nodesToVisit === (visitedCount + tmpLeaves)) {
43
42
if ( nodesToVisit === ( visitedCount + nbOfLeaves ) ) {
44
- // console.log(`old_level:${level}, tmpMax:${tmpMax}, max:${max}, visitedCount:${visitedCount}, tmpLeaves:${tmpLeaves}`)
45
- console . log ( `>>> tmpMax:${ tmpMax } , max:${ max } ` )
46
- if ( tmpMax > max ) {
47
- level = ( nodesToVisit / 2 ) + 1 ;
43
+ let tmpLevel = Math . log2 ( nodesToVisit ) + 1 ;
44
+ console . log ( `>>> tmpLevel:${ tmpLevel } , tmpMax:${ tmpMax } , max:${ max } ` )
45
+
46
+ if ( ( null !== tmpMax ) && ( tmpMax > max ) ) {
47
+ level = tmpLevel ;
48
48
max = tmpMax ;
49
49
}
50
50
51
51
nodesToVisit *= 2 ;
52
- // visitedCount = nodesToVisit - (tmpLeaves * 2) - nbOfLeaves;
53
52
visitedCount = 0 ;
54
- tmpMax = 0 ;
53
+ tmpMax = null ;
55
54
nbOfLeaves = ( nbOfLeaves + tmpLeaves ) * 2 ;
56
55
tmpLeaves = 0 ;
57
56
}
0 commit comments