Created
January 6, 2026 21:34
-
-
Save tatsuyax25/eddbf2b307cf6ff44312164236833a9a to your computer and use it in GitHub Desktop.
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for a binary tree node. | |
| * function TreeNode(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} | |
| */ | |
| var maxLevelSum = function(root) { | |
| // Edge case: if the tree is empty (not typical for this problem) | |
| if (!root) return 0; | |
| // Queue for BFS - start with the root | |
| const queue = [root] | |
| let currentLevel = 1; // Levels are 1-indexed | |
| let maxSum = -Infinity; // Works even if all values are negative | |
| let maxLevel = 1; | |
| // Standard BFS loop | |
| while (queue.length > 0) { | |
| const levelSize = queue.length; // Number of nodes at this level | |
| let levelSum = 0; | |
| // Process exactly 'levelSize' nodes | |
| for (let i = 0; i < levelSize; i++) { | |
| const node = queue.shift(); | |
| levelSum += node.val; | |
| // Add children for next level | |
| if (node.left) queue.push(node.left); | |
| if (node.right) queue.push(node.right); | |
| } | |
| // After finishing this level, check if it's the best so far | |
| if (levelSum > maxSum) { | |
| maxSum = levelSum; | |
| maxLevel = currentLevel; | |
| } | |
| currentLevel++; // Move to the next level | |
| } | |
| return maxLevel; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment