-
Notifications
You must be signed in to change notification settings - Fork 2
/
maxLevelSum.ts
57 lines (44 loc) · 1.5 KB
/
maxLevelSum.ts
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
56
57
import type { TreeNode } from '~/utils/binary-tree';
type MaxLevelSum = (root: TreeNode | null) => number;
/**
* Accepted
*/
export const maxLevelSum: MaxLevelSum = (root) => {
// If the tree is empty, return 0 as there are no levels
if (!root) return 0;
// Initialize maxSum with the root's value and maxLevel as 1 (root level)
let maxSum = root.val;
let maxLevel = 1;
// Start at level 1
let currentLevel = 1;
// Initialize the queue for BFS with the root node
const queue: TreeNode[] = [root];
// Perform BFS until the queue is empty
while (queue.length > 0) {
// Determine the number of nodes at the current level
const levelSize = queue.length;
let levelSum = 0;
// Process each node at the current level
for (let i = 0; i < levelSize; i++) {
// Dequeue the front node
const node = queue.shift();
if (node) {
// Accumulate the sum of values at this level
levelSum += node.val;
// Enqueue left child if it exists
if (node.left) queue.push(node.left);
// Enqueue right child if it exists
if (node.right) queue.push(node.right);
}
}
// After processing the current level, check if its sum is greater than the maxSum found so far
if (levelSum > maxSum) {
maxSum = levelSum; // Update maxSum
maxLevel = currentLevel; // Update maxLevel to the current level
}
// Move to the next level
currentLevel += 1;
}
// Return the level with the maximum sum
return maxLevel;
};