-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1161-maximum-level-sum-of-a-binary-tree.js
More file actions
43 lines (36 loc) · 1.18 KB
/
1161-maximum-level-sum-of-a-binary-tree.js
File metadata and controls
43 lines (36 loc) · 1.18 KB
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
/**
* Maximum Level Sum of a Binary Tree
* Time Complexity: O(N)
* Space Complexity: O(W)
*/
var maxLevelSum = function (root) {
let queueForTraversal = [];
if (root) {
queueForTraversal.push(root);
}
let maximalSumFound = -Infinity;
let levelWithMaximalSum = 0;
let currentLevelNumber = 1;
while (queueForTraversal.length > 0) {
let nodeQueueSize = queueForTraversal.length;
let sumForThisLevel = 0;
for (let iteratorVariable = 0; iteratorVariable < nodeQueueSize; iteratorVariable++) {
let currentNode = queueForTraversal.shift();
sumForThisLevel += currentNode.val;
let leftNodeChild = currentNode.left;
if (leftNodeChild) {
queueForTraversal.push(leftNodeChild);
}
let rightNodeChild = currentNode.right;
if (rightNodeChild) {
queueForTraversal.push(rightNodeChild);
}
}
if (sumForThisLevel > maximalSumFound) {
maximalSumFound = sumForThisLevel;
levelWithMaximalSum = currentLevelNumber;
}
currentLevelNumber++;
}
return levelWithMaximalSum;
};