Find the Level of Tree with Minimum Sum Problem
#3157
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3157.
Given the root of a binary tree root where each node has a value, return the level of the tree that has the minimum sum of values among all the levels (in case of a tie, return the lowest level).
Note that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.
Example 1:
Input: root = [50,6,2,30,80,7]
Output: 2
Explanation:

Example 2:
Input: root = [36,17,10,null,null,24]
Output: 3
Explanation:

Example 3:
Input: root = [5,null,5,null,5]
Output: 1
Explanation:

Constraints:
- The number of nodes in the tree is in the range
[1, 10^5]. 1 <= Node.val <= 10^9
Solution
Approach: BFS
Traverse the tree level by level, add up the values on each level, and remember the level with the smallest sum. Using a strict comparison keeps the smallest level number when sums tie.
Complexity: O(n) time and O(n) extra space, where n is the number of nodes.
from collections import deque
from math import inf
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minimumLevel(self, root: Optional[TreeNode]) -> int:
q = deque([root])
ans = 0
level, s = 1, inf
while q:
t = 0
for _ in range(len(q)):
node = q.popleft()
t += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if s > t:
s = t
ans = level
level += 1
return ans