LeetCode 3157: Find the Level of Tree with Minimum Sum Solution
Master LeetCode problem 3157 (Find the Level of Tree with Minimum Sum), 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.
3157. Find the Level of Tree with Minimum Sum
Problem Explanation
Explanation:
To solve this problem, we can perform a level-order traversal of the tree while keeping track of the sum of each level. We can use a queue to traverse the tree level by level. At each level, we calculate the sum of nodes and compare it with the minimum sum found so far. If a level has a smaller sum, we update the minimum sum and the corresponding level number.
Algorithm:
- Initialize a queue for level-order traversal and a variable to store the minimum sum with an initial value of Integer.MAX_VALUE and another variable to store the level number with an initial value of 0.
- While the queue is not empty, iterate through the nodes at the current level.
- For each node, add its value to the sum of the current level.
- If the sum of the current level is less than the minimum sum so far, update the minimum sum and the level number accordingly.
- Enqueue the children of the current node if they exist.
- Repeat steps 2-5 until all levels are processed.
- Return the level number with the minimum sum.
Time Complexity: O(N) where N is the number of nodes in the tree. Space Complexity: O(N) for the queue to store nodes at each level.
:
Solution Code
class Solution {
public int minLevelSum(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int level = 0, minLevel = 0, minSum = Integer.MAX_VALUE;
while (!queue.isEmpty()) {
level++;
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 < minSum) {
minSum = sum;
minLevel = level;
}
}
return minLevel;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3157 (Find the Level of Tree with Minimum Sum)?
This page provides optimized solutions for LeetCode problem 3157 (Find the Level of Tree with Minimum Sum) 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 3157 (Find the Level of Tree with Minimum Sum)?
The time complexity for LeetCode 3157 (Find the Level of Tree with Minimum Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3157 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3157 in Java, C++, or Python.