LeetCode 1161: Maximum Level Sum of a Binary Tree Solution
Master LeetCode problem 1161 (Maximum Level Sum of a Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1161. Maximum Level Sum of a Binary Tree
Problem Explanation
Explanation:
To solve this problem, we can perform a level order traversal of the binary tree while keeping track of the sum of values at each level. We can use a queue to traverse the tree level by level. At each level, we calculate the sum of values and compare it with the maximum sum seen so far. Finally, we return the level with the maximum sum.
- Initialize a queue to perform level order traversal.
- Initialize variables to store the maximum sum and the level with the maximum sum.
- Perform a level order traversal of the binary tree:
- For each level, calculate the sum of values.
- Update the maximum sum and the level with the maximum sum.
- Return the level with the maximum sum.
Time Complexity: O(N), where N is the number of nodes in the binary tree. Space Complexity: O(N), where N is the number of nodes in the binary tree.
:
Solution Code
class Solution {
public int maxLevelSum(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int level = 1;
int maxLevel = 1;
int maxSum = Integer.MIN_VALUE;
while (!queue.isEmpty()) {
int size = queue.size();
int sum = 0;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
sum += node.val;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
if (sum > maxSum) {
maxSum = sum;
maxLevel = level;
}
level++;
}
return maxLevel;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1161 (Maximum Level Sum of a Binary Tree)?
This page provides optimized solutions for LeetCode problem 1161 (Maximum Level Sum of a Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1161 (Maximum Level Sum of a Binary Tree)?
The time complexity for LeetCode 1161 (Maximum Level Sum of a Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1161 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1161 in Java, C++, or Python.