# Given a binary tree, return the level of the tree with minimum sum.

By | January 22, 2024

Java:

``````
import java.util.Queue;
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeMinLevelSum {
public int minLevelSum(TreeNode root) {
if (root == null) return 0;
int minSum = Integer.MAX_VALUE;
int minLevel = 0;
int level = 0;
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
int currentSum = 0;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
currentSum += node.val;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
if (currentSum < minSum) {
minSum = currentSum;
minLevel = level;
}
level++;
}
return minLevel;
}
}``````
``````// Example usage:
// Assuming you have a tree root
// int level = minLevelSum(root);``````

Javascript:

``````class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function minLevelSum(root) {
if (!root) return 0;
let minSum = Infinity;
let minLevel = 0;
let level = 0;
const queue = [root];
while (queue.length > 0) {
const size = queue.length;
let currentSum = 0;
for (let i = 0; i < size; i++) {
const node = queue.shift();
currentSum += node.val;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
if (currentSum < minSum) {
minSum = currentSum;
minLevel = level;
}
level++;
}
return minLevel;
}``````
``````// Example usage:
// Assuming you have a tree root
// const level = minLevelSum(root);``````

Python:

``````class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def min_level_sum(root):
if not root:
return 0
min_sum = float('inf')
min_level = 0
level = 0
queue = [root]
while queue:
size = len(queue)
current_sum = 0
for i in range(size):
node = queue.pop(0)
current_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if current_sum < min_sum:
min_sum = current_sum
min_level = level
level += 1
return min_level
``````
``````# Example usage: # Assuming you have a tree root #
level = min_level_sum(root)``````