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.
?
Input: root = [1,7,0,7,-8,null,null]
Output: 2
**Explanation: **
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.
Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2
From: LeetCode
Link: 1161. Maximum Level Sum of a Binary Tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxLevelSum(struct TreeNode* root) {
if (root == NULL) return 1;
// Dynamically allocate a queue to hold pointers to TreeNodes
int queueSize = 1024; // initial size
struct TreeNode** queue = (struct TreeNode**)malloc(queueSize * sizeof(struct TreeNode*));
if (!queue) return -1; // allocation failed
int front = 0, rear = 0, level = 1, maxSum = root->val, maxLevel = 1, currentSum = 0;
// Enqueue the root and a NULL marker for level 1
queue[rear++] = root;
queue[rear++] = NULL;
while (front < rear) {
struct TreeNode* node = queue[front++];
if (node == NULL) {
if (currentSum > maxSum) {
maxSum = currentSum;
maxLevel = level;
}
// Reset current sum for next level
currentSum = 0;
// Increase level number
level++;
// Continue only if there are more nodes to process
if (front < rear) {
queue[rear++] = NULL; // Marker for the next level
}
} else {
// Add the node's value to the current level sum
currentSum += node->val;
// Enqueue child nodes
if (node->left) {
if (rear >= queueSize) {
// Increase queue size
queueSize *= 2;
queue = (struct TreeNode**)realloc(queue, queueSize * sizeof(struct TreeNode*));
if (!queue) return -1; // reallocation failed
}
queue[rear++] = node->left;
}
if (node->right) {
if (rear >= queueSize) {
// Increase queue size
queueSize *= 2;
queue = (struct TreeNode**)realloc(queue, queueSize * sizeof(struct TreeNode*));
if (!queue) return -1; // reallocation failed
}
queue[rear++] = node->right;
}
}
}
free(queue); // Free the queue
return maxLevel;
}