Skip to main content
Back to problems
#3157
Medium Algorithms

Find the level of tree with minimum sum

Tree Depth-First Search Breadth-First Search Binary Tree
69.6% acceptance
Mar 31, 2026
19
3
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
// use std::rc::Rc;
// use std::cell::RefCell;

use std::rc::Rc;
use std::cell::RefCell;

impl Solution {
  pub fn minimum_level(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    let mut queue = std::collections::VecDeque::new();
    if let Some(r) = root {
      queue.push_back(r);
    }
    let mut min_sum = i64::MAX;
    let mut min_level = 0;
    let mut level = 0;
    while !queue.is_empty() {
      level += 1;
      let size = queue.len();
      let mut sum = 0i64;
      for _ in 0..size {
        let node = queue.pop_front().unwrap();
        let node = node.borrow();
        sum += node.val as i64;
        if let Some(ref left) = node.left {
          queue.push_back(left.clone());
        }
        if let Some(ref right) = node.right {
          queue.push_back(right.clone());
        }
      }
      if sum < min_sum {
        min_sum = sum;
        min_level = level;
      }
    }
    min_level
  }
}