-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
55 lines (48 loc) · 1.22 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class TreeNode {
constructor(val, left, right) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
}
/**
* @param {TreeNode} root
* @return {number}
*/
const maxLevelSum = (root) => {
let queue = [root], level = 1, max = root.val, tmpMax = 0,
nbOfLeaves = 0, tmpLeaves = 0, nodesToVisit = 2, visitedCount = 0;
while (queue.length > 0) {
let curr = queue.shift(), left = curr.left, right = curr.right;
if (undefined !== left) {
visitedCount++;
if (null !== left) {
tmpMax += left.val;
queue.push(left);
} else {
tmpLeaves++;
}
}
if (undefined !== right) {
visitedCount++;
if (null !== right) {
tmpMax += right.val;
queue.push(right);
} else {
tmpLeaves++;
}
}
if (nodesToVisit === (visitedCount + nbOfLeaves)) {
if ((null !== tmpMax) && (tmpMax > max)) {
level = Math.log2(nodesToVisit) + 1;
max = tmpMax;
}
nodesToVisit *= 2;
nbOfLeaves = (nbOfLeaves + tmpLeaves) * 2;
visitedCount = 0;
tmpLeaves = 0;
tmpMax = null;
}
}
return level;
};